mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
fix(producer): count composition ids once for nested hosts, and charge the entry page's elements (#8335)
* test(producer): a nested host's id search and the entry page's elements stay bounded * fix(producer): count composition ids once for nested hosts, and charge the entry page's elements
This commit is contained in:
@@ -59,6 +59,7 @@ const limitText = `One render generates at most ${megabytes(MAX_EXPANDED_COMPOSI
|
||||
|
||||
export const REMOTE_SCRIPTS = "remote scripts";
|
||||
export const REMOTE_STYLESHEETS = "remote stylesheets";
|
||||
export const ENTRY_PAGE = "the entry page";
|
||||
|
||||
function generatedTooLarge(file: string, bytes: number): string {
|
||||
if (file === "composition variables") {
|
||||
@@ -98,7 +99,9 @@ export class CompositionExpansionBudget {
|
||||
this.elements += count;
|
||||
if (this.elements <= MAX_EXPANDED_ELEMENTS) return;
|
||||
throw new CompositionTooLargeError(
|
||||
`Sub-composition mounts, ending at "${file}", add up to ${this.elements} elements. ` +
|
||||
(file === ENTRY_PAGE
|
||||
? `The entry page holds ${this.elements} elements. `
|
||||
: `Sub-composition mounts, ending at "${file}", add up to ${this.elements} elements. `) +
|
||||
`One render inlines at most ${MAX_EXPANDED_ELEMENTS} elements. Mount large or repeated scenes fewer times.`,
|
||||
{
|
||||
bytes: this.bytes,
|
||||
|
||||
@@ -101,6 +101,7 @@ export {
|
||||
export {
|
||||
assertCompositionFileSize,
|
||||
CompositionExpansionBudget,
|
||||
ENTRY_PAGE,
|
||||
isCompositionTooLargeError,
|
||||
MAX_COMPOSITION_HTML_BYTES,
|
||||
MAX_EXPANDED_COMPOSITION_BYTES,
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { parseHTML } from "linkedom";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { MAX_EXPANDED_ELEMENTS } from "@hyperframes/core/compiler";
|
||||
import { compileForRender } from "./htmlCompiler.js";
|
||||
import { extractSafeRenderErrorCode } from "./safeRenderErrorCode.js";
|
||||
|
||||
const dirs: string[] = [];
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const root = (body: string) =>
|
||||
`<!doctype html><html><head></head><body><main data-composition-id="root" data-start="0" data-duration="1" data-width="16" data-height="16">${body}</main></body></html>`;
|
||||
const mount = (id: string, src: string) =>
|
||||
`<div data-composition-id="${id}" data-composition-src="${src}" data-start="0" data-duration="1"></div>`;
|
||||
|
||||
function compile(files: Record<string, string>) {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hf-late-host-ids-"));
|
||||
dirs.push(dir);
|
||||
for (const [name, html] of Object.entries(files)) writeFileSync(join(dir, name), html);
|
||||
return compileForRender(dir, join(dir, "index.html"), join(dir, "out"), {
|
||||
allowSystemFontCapture: false,
|
||||
});
|
||||
}
|
||||
|
||||
// fails without the fix: each candidate id of a nested host rescanned the whole page.
|
||||
it("finds a nested host's id in reads proportional to the page, whatever ids it already holds", async () => {
|
||||
const taken = 2000;
|
||||
const element = Object.getPrototypeOf(parseHTML("<p></p>").document.querySelector("p"));
|
||||
const owner = (function find(proto) {
|
||||
return Object.prototype.hasOwnProperty.call(proto, "getAttribute")
|
||||
? proto
|
||||
: find(Object.getPrototypeOf(proto));
|
||||
})(element);
|
||||
const read = owner.getAttribute;
|
||||
let idReads = 0;
|
||||
vi.spyOn(owner, "getAttribute").mockImplementation(function (this: Element, name: string) {
|
||||
if (name === "data-composition-id") idReads += 1;
|
||||
return read.call(this, name);
|
||||
});
|
||||
const held = Array.from(
|
||||
{ length: taken },
|
||||
(_, i) => `<i data-composition-id="card__hf${i + 1}"></i>`,
|
||||
);
|
||||
|
||||
const { html } = await compile({
|
||||
"index.html": root(held.join("") + mount("outer", "outer.html")),
|
||||
"outer.html": `<template><div data-composition-id="outer" data-width="16" data-height="16">${mount("card", "card.html")}</div></template>`,
|
||||
"card.html": `<template><div data-composition-id="card" data-width="16" data-height="16"><b>card</b></div></template>`,
|
||||
});
|
||||
|
||||
expect(idReads).toBeLessThan(taken * 50);
|
||||
const assigned = `card__hf${taken + 1}`;
|
||||
expect(html.split(`data-composition-id="${assigned}"`).length - 1).toBe(1);
|
||||
}, 60_000);
|
||||
|
||||
// fails without the fix: only elements copied by mounts were counted, so the entry page's own were never bounded.
|
||||
it("counts the entry page's own elements against the element cap", async () => {
|
||||
const error = await compile({
|
||||
"index.html": root("<i></i>".repeat(MAX_EXPANDED_ELEMENTS)),
|
||||
}).then(
|
||||
() => undefined,
|
||||
(thrown: unknown) => thrown,
|
||||
);
|
||||
|
||||
expect(extractSafeRenderErrorCode(error)).toBe("COMPOSITION_TOO_LARGE");
|
||||
expect(error).toMatchObject({
|
||||
publicMetadata: { limitElements: MAX_EXPANDED_ELEMENTS, exceeded: "elements" },
|
||||
});
|
||||
}, 60_000);
|
||||
@@ -147,13 +147,14 @@ describe("composition expansion budget", () => {
|
||||
const perScene = 1000;
|
||||
const scene = `<template><div data-composition-id="scene">${"<i></i>".repeat(perScene - 2)}</div></template>`;
|
||||
const mounts = Math.floor(MAX_EXPANDED_ELEMENTS / perScene) + 1;
|
||||
const error = await compileError(
|
||||
project({ "index.html": rootMounting("scene.html", mounts), "scene.html": scene }),
|
||||
);
|
||||
const entry = rootMounting("scene.html", mounts);
|
||||
const entryElements = parseHTML(entry).document.querySelectorAll("*").length;
|
||||
const copied = Math.floor((MAX_EXPANDED_ELEMENTS - entryElements) / perScene) + 1;
|
||||
const error = await compileError(project({ "index.html": entry, "scene.html": scene }));
|
||||
expect(extractSafeRenderErrorCode(error)).toBe("COMPOSITION_TOO_LARGE");
|
||||
expect(error).toMatchObject({
|
||||
publicMetadata: {
|
||||
elements: mounts * perScene,
|
||||
elements: entryElements + copied * perScene,
|
||||
limitElements: MAX_EXPANDED_ELEMENTS,
|
||||
exceeded: "elements",
|
||||
},
|
||||
|
||||
@@ -107,6 +107,7 @@ import { extractMediaMetadata, extractAudioMetadata } from "../utils/ffprobe.js"
|
||||
import {
|
||||
assertCompositionFileSize,
|
||||
CompositionExpansionBudget,
|
||||
ENTRY_PAGE,
|
||||
REMOTE_SCRIPTS,
|
||||
REMOTE_STYLESHEETS,
|
||||
} from "@hyperframes/core/compiler";
|
||||
@@ -1139,15 +1140,32 @@ function promoteCssImportsToLinkTags(html: string): string {
|
||||
}
|
||||
|
||||
class ProducerHostIdentityMap extends Map<Element, BundledHostCompositionIdentity> {
|
||||
readonly #document: Document;
|
||||
readonly #lateInstanceByCompositionId = new Map<string, number>();
|
||||
/** How many elements carry each composition id: the page once, then each mount's copy once. */
|
||||
readonly #idCounts = new Map<string, number>();
|
||||
/** Hosts whose copied content has not been counted yet; the inliner fills a host after asking for it. */
|
||||
#uncounted: ParentNode[];
|
||||
|
||||
constructor(document: Document, initialHosts: Element[]) {
|
||||
super(assignBundledRuntimeCompositionIds(initialHosts));
|
||||
this.#document = document;
|
||||
this.#uncounted = [document];
|
||||
}
|
||||
|
||||
#countUncopied(): void {
|
||||
for (const root of this.#uncounted.splice(0)) {
|
||||
for (const element of Array.from(root.querySelectorAll("[data-composition-id]"))) {
|
||||
this.#adjust(element.getAttribute("data-composition-id"), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#adjust(id: string | null, by: number): void {
|
||||
if (id) this.#idCounts.set(id, (this.#idCounts.get(id) ?? 0) + by);
|
||||
}
|
||||
|
||||
override get(host: Element): BundledHostCompositionIdentity | undefined {
|
||||
this.#countUncopied();
|
||||
this.#uncounted.push(host);
|
||||
const existing = super.get(host);
|
||||
if (existing) return existing;
|
||||
|
||||
@@ -1166,21 +1184,20 @@ class ProducerHostIdentityMap extends Map<Element, BundledHostCompositionIdentit
|
||||
return identity;
|
||||
}
|
||||
|
||||
const ownId = host.getAttribute("data-composition-id");
|
||||
const heldByOthers = (id: string) => (this.#idCounts.get(id) ?? 0) - (id === ownId ? 1 : 0) > 0;
|
||||
let instanceIndex = this.#lateInstanceByCompositionId.get(authoredCompositionId) || 0;
|
||||
let runtimeCompositionId: string;
|
||||
do {
|
||||
instanceIndex += 1;
|
||||
runtimeCompositionId = `${authoredCompositionId}__hf${instanceIndex}`;
|
||||
} while (
|
||||
Array.from(this.#document.querySelectorAll("[data-composition-id]")).some(
|
||||
(element) =>
|
||||
element !== host && element.getAttribute("data-composition-id") === runtimeCompositionId,
|
||||
)
|
||||
);
|
||||
} while (heldByOthers(runtimeCompositionId));
|
||||
this.#lateInstanceByCompositionId.set(authoredCompositionId, instanceIndex);
|
||||
|
||||
host.setAttribute("data-hf-original-composition-id", authoredCompositionId);
|
||||
host.setAttribute("data-composition-id", runtimeCompositionId);
|
||||
this.#adjust(ownId, -1);
|
||||
this.#adjust(runtimeCompositionId, 1);
|
||||
const identity = { authoredCompositionId, runtimeCompositionId };
|
||||
this.set(host, identity);
|
||||
return identity;
|
||||
@@ -1275,6 +1292,7 @@ function inlineSubCompositions(
|
||||
budget: CompositionExpansionBudget,
|
||||
): { html: string; variablesByComp: Record<string, Record<string, unknown>> } {
|
||||
const { document } = parseHTML(html);
|
||||
budget.chargeElements(ENTRY_PAGE, document.querySelectorAll("*").length);
|
||||
const head = document.querySelector("head");
|
||||
const body = document.querySelector("body");
|
||||
const hosts = Array.from(document.querySelectorAll("[data-composition-src]"));
|
||||
|
||||
Reference in New Issue
Block a user