mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
perf(studio-server): a root preview's parse passes run off the request thread (#7934)
* perf(studio-server): a root preview's parse passes run off the request thread * test(studio-server): a root build's page passes counted off the request thread, not timed * chore(studio-server): the root deadline's name says it; no comment over the ratchet
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
// The preview build passes that parse the page, run on the build worker (subCompositionWorker.ts).
|
||||
import { isCompositionTooLargeError } from "@hyperframes/core/compiler/composition-size-limit";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { addScenePartsManifest } from "@hyperframes/core/compiler";
|
||||
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
|
||||
import {
|
||||
injectStudioPreviewAugmentations,
|
||||
withPreviewBase,
|
||||
withPreviewRuntime,
|
||||
} from "../routes/preview.js";
|
||||
import { previewReferences } from "./previewReads.js";
|
||||
import { injectPreviewVariables } from "./previewVariables.js";
|
||||
import { withRootImportMap } from "./rootImportMap.js";
|
||||
import { buildSubCompositionHtml } from "./subComposition.js";
|
||||
import type {
|
||||
BaseJob,
|
||||
BuildJob,
|
||||
FinishJob,
|
||||
PartsJob,
|
||||
SubCompositionJob,
|
||||
} from "./subCompositionBuild.js";
|
||||
|
||||
/** The page with its runtime and the files it names, hf-ids pinned to the source's; null once the file is gone. */
|
||||
function buildOrRefuse(buildPage: () => string | null): string | { refused: string } | null {
|
||||
try {
|
||||
return buildPage();
|
||||
} catch (error) {
|
||||
if (isCompositionTooLargeError(error)) return { refused: error.message };
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
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)) {
|
||||
try {
|
||||
pinned = ensureHfIds(readFileSync(compFile, "utf-8"));
|
||||
} catch {
|
||||
return null; // removed between the route's stat and this read
|
||||
}
|
||||
}
|
||||
const built = buildOrRefuse(() =>
|
||||
buildSubCompositionHtml(projectDir, compPath, runtimeUrl, baseHref, pinned, gsapBaseUrl),
|
||||
);
|
||||
if (typeof built !== "string") return built;
|
||||
const html = withPreviewRuntime(withRootImportMap(built, baseHref), runtimeUrl);
|
||||
return { html, references: [...previewReferences(html)] };
|
||||
}
|
||||
|
||||
function finish({
|
||||
html,
|
||||
runtimeUrl,
|
||||
signature,
|
||||
projectDir,
|
||||
compPath,
|
||||
options,
|
||||
variables,
|
||||
}: FinishJob): string {
|
||||
const augmented = injectStudioPreviewAugmentations(
|
||||
ensureHfIds(html),
|
||||
runtimeUrl,
|
||||
signature,
|
||||
projectDir,
|
||||
compPath,
|
||||
options,
|
||||
);
|
||||
return variables ? injectPreviewVariables(augmented, variables) : augmented;
|
||||
}
|
||||
|
||||
/** The root page under its base and runtime, with the files it names. */
|
||||
function base({ html, projectId, runtimeUrl }: BaseJob) {
|
||||
const based = withPreviewRuntime(withPreviewBase(html, projectId), runtimeUrl);
|
||||
return { html: based, references: [...previewReferences(based)] };
|
||||
}
|
||||
|
||||
const parts = ({ html, ignore }: PartsJob) => addScenePartsManifest(html, ignore);
|
||||
|
||||
/** One build job's result, on whichever thread calls it (the build worker, or a test). */
|
||||
export function runPreviewJob(job: SubCompositionJob) {
|
||||
switch (job.kind) {
|
||||
case "build":
|
||||
return build(job);
|
||||
case "base":
|
||||
return base(job);
|
||||
case "finish":
|
||||
return finish(job);
|
||||
case "parts":
|
||||
return parts(job);
|
||||
default:
|
||||
return job satisfies never;
|
||||
}
|
||||
}
|
||||
@@ -74,10 +74,6 @@ export function recordPreviewRead(projectDir: string, filePath: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
export function recordPreviewReferences(projectDir: string, html: string): void {
|
||||
for (const path of previewReferences(html)) recordPreviewRead(projectDir, path);
|
||||
}
|
||||
|
||||
export function previewReferences(html: string): Set<string> {
|
||||
const named = new Set<string>();
|
||||
const add = (reference: string) => {
|
||||
|
||||
@@ -24,10 +24,25 @@ export interface FinishJob {
|
||||
variables?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export type SubCompositionJob = BuildJob | FinishJob;
|
||||
export interface BaseJob {
|
||||
kind: "base";
|
||||
html: string;
|
||||
projectId: string;
|
||||
runtimeUrl: string;
|
||||
}
|
||||
|
||||
export interface PartsJob {
|
||||
kind: "parts";
|
||||
html: string;
|
||||
ignore: string[];
|
||||
}
|
||||
|
||||
export type SubCompositionJob = BuildJob | BaseJob | FinishJob | PartsJob;
|
||||
type Result<J> = J extends BuildJob
|
||||
? { html: string; references: string[] } | { refused: string } | null
|
||||
: string;
|
||||
: J extends BaseJob
|
||||
? { html: string; references: string[] }
|
||||
: string;
|
||||
|
||||
export class SubCompositionDeadlineError extends Error {
|
||||
constructor(compPath: string) {
|
||||
@@ -37,6 +52,7 @@ export class SubCompositionDeadlineError extends Error {
|
||||
}
|
||||
|
||||
export const SUB_COMPOSITION_DEADLINE_MS = 30_000;
|
||||
export const ROOT_PREVIEW_DEADLINE_MS = 120_000;
|
||||
|
||||
interface Pending {
|
||||
job: SubCompositionJob;
|
||||
|
||||
@@ -1,66 +1,11 @@
|
||||
// Builds sub-composition preview pages off the request thread; the route keeps the host's transform and media probes.
|
||||
import { readFileSync } from "node:fs";
|
||||
// Builds root and sub-composition preview pages off the request thread; the route keeps transforms and media probes.
|
||||
import { parentPort } from "node:worker_threads";
|
||||
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
|
||||
import { injectStudioPreviewAugmentations, withPreviewRuntime } from "../routes/preview.js";
|
||||
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[] } | { refused: string } | null {
|
||||
const { projectDir, compPath, compFile, runtimeUrl, baseHref, gsapBaseUrl } = job;
|
||||
let pinned: string | undefined;
|
||||
if (/\.html?$/i.test(compPath)) {
|
||||
try {
|
||||
pinned = ensureHfIds(readFileSync(compFile, "utf-8"));
|
||||
} catch {
|
||||
return null; // removed between the route's stat and this read
|
||||
}
|
||||
}
|
||||
const built = buildOrRefuse(() =>
|
||||
buildSubCompositionHtml(projectDir, compPath, runtimeUrl, baseHref, pinned, gsapBaseUrl),
|
||||
);
|
||||
if (typeof built !== "string") return built;
|
||||
const html = withPreviewRuntime(withRootImportMap(built, baseHref), runtimeUrl);
|
||||
return { html, references: [...previewReferences(html)] };
|
||||
}
|
||||
|
||||
function finish({
|
||||
html,
|
||||
runtimeUrl,
|
||||
signature,
|
||||
projectDir,
|
||||
compPath,
|
||||
options,
|
||||
variables,
|
||||
}: FinishJob): string {
|
||||
const augmented = injectStudioPreviewAugmentations(
|
||||
ensureHfIds(html),
|
||||
runtimeUrl,
|
||||
signature,
|
||||
projectDir,
|
||||
compPath,
|
||||
options,
|
||||
);
|
||||
return variables ? injectPreviewVariables(augmented, variables) : augmented;
|
||||
}
|
||||
import { runPreviewJob } from "./previewJobs.js";
|
||||
import type { SubCompositionJob } from "./subCompositionBuild.js";
|
||||
|
||||
parentPort?.on("message", ({ id, job }: { id: number; job: SubCompositionJob }) => {
|
||||
try {
|
||||
parentPort?.postMessage({ id, result: job.kind === "build" ? build(job) : finish(job) });
|
||||
parentPort?.postMessage({ id, result: runPreviewJob(job) });
|
||||
} catch (error) {
|
||||
parentPort?.postMessage({ id, error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
|
||||
@@ -20,6 +20,13 @@ vi.mock("linkedom", async (actual) => {
|
||||
};
|
||||
});
|
||||
|
||||
// The parses run on the build worker in the app; here its jobs run in-process, where the count can see them.
|
||||
vi.mock("../helpers/subCompositionBuild", async (actual) => ({
|
||||
...(await actual<typeof import("../helpers/subCompositionBuild")>()),
|
||||
runOffThread: async (job: import("../helpers/subCompositionBuild").SubCompositionJob) =>
|
||||
(await import("../helpers/previewJobs")).runPreviewJob(job),
|
||||
}));
|
||||
|
||||
const { registerPreviewRoutes } = await import("./preview");
|
||||
|
||||
it("parses a stamped page once per preview build (the read-tracking walk) when it has no images, <base> or scene parts", async () => {
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// @vitest-environment node
|
||||
import { afterAll, expect, it, vi } from "vitest";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { StudioApiAdapter } from "../types";
|
||||
|
||||
// Each page pass the request thread runs on a whole page, counted here; the build worker loads its own copies.
|
||||
const onThread = vi.hoisted(() => ({ passes: [] as string[], minLength: Infinity }));
|
||||
const counted =
|
||||
<A extends unknown[], R>(name: string, real: (html: string, ...rest: A) => R) =>
|
||||
(html: string, ...rest: A): R => {
|
||||
if (typeof html === "string" && html.length >= onThread.minLength) onThread.passes.push(name);
|
||||
return real(html, ...rest);
|
||||
};
|
||||
vi.mock("linkedom", async (actual) => {
|
||||
const real = await actual<typeof import("linkedom")>();
|
||||
return { ...real, parseHTML: counted("parseHTML", real.parseHTML as (html: string) => unknown) };
|
||||
});
|
||||
vi.mock("@hyperframes/parsers/hf-ids", async (actual) => {
|
||||
const real = await actual<typeof import("@hyperframes/parsers/hf-ids")>();
|
||||
return { ...real, ensureHfIds: counted("ensureHfIds", real.ensureHfIds) };
|
||||
});
|
||||
vi.mock("@hyperframes/core/compiler", async (actual) => {
|
||||
const real = await actual<typeof import("@hyperframes/core/compiler")>();
|
||||
return {
|
||||
...real,
|
||||
addScenePartsManifest: counted("addScenePartsManifest", real.addScenePartsManifest),
|
||||
};
|
||||
});
|
||||
|
||||
const { createStudioApi } = await import("../createStudioApi");
|
||||
|
||||
const projectDir = mkdtempSync(join(tmpdir(), "hf-preview-root-off-thread-"));
|
||||
afterAll(() => rmSync(projectDir, { recursive: true, force: true }));
|
||||
const shapes = Array.from(
|
||||
{ length: 2_000 },
|
||||
(_, i) => `<path d="M${i % 97} ${i % 89}l9 1 6 8-3 9-8 1z" fill="hsl(${i % 360} 70% 55%)"/>`,
|
||||
).join("");
|
||||
const page = `<!doctype html><html><head></head><body><div id="root" data-composition-id="main" data-width="320" data-height="180"><svg viewBox="0 0 100 100">${shapes}</svg><p id="hello">Hi</p></div></body></html>`;
|
||||
writeFileSync(join(projectDir, "index.html"), page);
|
||||
|
||||
const adapter: StudioApiAdapter = {
|
||||
listProjects: () => [],
|
||||
resolveProject: async (id: string) => ({ id, dir: projectDir }),
|
||||
bundle: async () => page,
|
||||
lint: async () => ({ findings: [] }),
|
||||
runtimeUrl: "/api/runtime.js",
|
||||
rendersDir: () => join(projectDir, "renders"),
|
||||
startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/out.mp4" }),
|
||||
};
|
||||
|
||||
// fails without the fix: the root page's parse passes ran on the request thread, holding it for the whole build while
|
||||
// Desktop's capture window built a poster beside a playing film.
|
||||
it("a root preview, captured or not, is served whole with no page pass on the request thread", async () => {
|
||||
const api = createStudioApi(adapter);
|
||||
onThread.minLength = page.length / 2;
|
||||
for (const query of ["", "?hf-capture=1"]) {
|
||||
onThread.passes.length = 0;
|
||||
const res = await api.request(`http://localhost/projects/demo/preview${query}`);
|
||||
expect(res.status).toBe(200);
|
||||
const html = await res.text();
|
||||
expect(html).toMatch(/<p[^>]*data-hf-id="[^"]+"[^>]*>Hi<\/p>/);
|
||||
expect(onThread.passes).toEqual([]);
|
||||
}
|
||||
}, 120_000);
|
||||
@@ -40,10 +40,14 @@ import type { StudioApiAdapter } from "../types";
|
||||
import {
|
||||
affectsPreview,
|
||||
recordPreviewBuilt,
|
||||
previewReferences,
|
||||
recordPreviewRead,
|
||||
recordPreviewReferences,
|
||||
} from "../helpers/previewReads";
|
||||
|
||||
const recordPreviewReferences = (projectDir: string, html: string) => {
|
||||
for (const path of previewReferences(html)) recordPreviewRead(projectDir, path);
|
||||
};
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
@@ -7,7 +7,6 @@ import { join, resolve } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
AFTER_FONTS_SCRIPT_TYPE,
|
||||
addScenePartsManifest,
|
||||
RUNTIME_BOOTSTRAP_ATTR,
|
||||
insertBeforeCloseTag,
|
||||
insertRuntimeTag,
|
||||
@@ -53,6 +52,7 @@ import { openRangeEnd } from "../helpers/mediaRange.js";
|
||||
import { hasBaseElement } from "../helpers/subComposition.js";
|
||||
import {
|
||||
runOffThread,
|
||||
ROOT_PREVIEW_DEADLINE_MS,
|
||||
SUB_COMPOSITION_DEADLINE_MS,
|
||||
SubCompositionDeadlineError,
|
||||
withinDeadline,
|
||||
@@ -74,11 +74,7 @@ import {
|
||||
} from "../helpers/studioMotionRenderScript.js";
|
||||
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
|
||||
import { settledFileTag } from "../helpers/fileVersion.js";
|
||||
import {
|
||||
recordPreviewBuilt,
|
||||
recordPreviewRead,
|
||||
recordPreviewReferences,
|
||||
} from "../helpers/previewReads.js";
|
||||
import { recordPreviewBuilt, recordPreviewRead } from "../helpers/previewReads.js";
|
||||
import { isVariablesPayload, VARIABLES_PAYLOAD_ERROR } from "../helpers/variablesPayload.js";
|
||||
import { injectPreviewVariables } from "../helpers/previewVariables.js";
|
||||
import {
|
||||
@@ -483,7 +479,7 @@ export const PREVIEW_BUNDLE_OPTIONS = {
|
||||
const previewBaseHref = (projectId: string) =>
|
||||
`/api/projects/${encodeURIComponent(projectId)}/preview/`;
|
||||
|
||||
const withPreviewBase = (html: string, projectId: string) => {
|
||||
export const withPreviewBase = (html: string, projectId: string) => {
|
||||
const base = previewBaseHref(projectId);
|
||||
const mapped = withRootImportMap(withRootPathsRelative(html, base), base);
|
||||
return hasBaseElement(mapped) ? mapped : injectTagsAtHeadStart(mapped, `<base href="${base}">`);
|
||||
@@ -559,20 +555,42 @@ export function registerPreviewRoutes(
|
||||
mainCompositionPath = diskMain.compositionPath;
|
||||
}
|
||||
// <base> and root paths under it, before the runtime adds the server's own root path
|
||||
bundled = withPreviewRuntime(withPreviewBase(bundled, project.id), adapter.runtimeUrl);
|
||||
recordPreviewReferences(project.dir, bundled);
|
||||
const rootDeadline = performance.now() + ROOT_PREVIEW_DEADLINE_MS;
|
||||
const based = await runOffThread(
|
||||
{ kind: "base", html: bundled, projectId: project.id, runtimeUrl: adapter.runtimeUrl },
|
||||
rootDeadline,
|
||||
mainCompositionPath,
|
||||
);
|
||||
bundled = based.html;
|
||||
for (const path of based.references) recordPreviewRead(project.dir, path);
|
||||
recordPreviewBuilt(project.dir);
|
||||
|
||||
// Also covers elements the adapter injected; ids already present are kept.
|
||||
bundled = injectStudioPreviewAugmentations(
|
||||
ensureHfIds(await transformPreviewHtml(bundled, adapter, project, mainCompositionPath)),
|
||||
adapter.runtimeUrl,
|
||||
// The passes that parse the page run on the build worker (a capture page builds while a film plays); the
|
||||
// host's transform and the media probes stay here.
|
||||
const transformed = await transformPreviewHtml(
|
||||
bundled,
|
||||
adapter,
|
||||
project,
|
||||
mainCompositionPath,
|
||||
);
|
||||
const options = { capture, gsapBaseUrl, sandboxedCapture: sandboxThumbnailCaptures };
|
||||
const job = {
|
||||
runtimeUrl: adapter.runtimeUrl,
|
||||
signature,
|
||||
project.dir,
|
||||
projectDir: project.dir,
|
||||
compPath: mainCompositionPath,
|
||||
};
|
||||
bundled = await runOffThread(
|
||||
{
|
||||
kind: "finish",
|
||||
html: transformed,
|
||||
...job,
|
||||
options,
|
||||
...(previewVariables && { variables: previewVariables }),
|
||||
},
|
||||
rootDeadline,
|
||||
mainCompositionPath,
|
||||
{ capture, gsapBaseUrl, sandboxedCapture: sandboxThumbnailCaptures },
|
||||
);
|
||||
if (previewVariables) bundled = injectPreviewVariables(bundled, previewVariables);
|
||||
bundled = await injectMediaCodecMap(
|
||||
bundled,
|
||||
adapter,
|
||||
@@ -580,7 +598,12 @@ export function registerPreviewRoutes(
|
||||
mainCompositionPath,
|
||||
mediaCodecProbeCache,
|
||||
);
|
||||
bundled = addScenePartsManifest(bundled, [`meta[name="${PROJECT_SIGNATURE_META}"]`]);
|
||||
const ignore = [`meta[name="${PROJECT_SIGNATURE_META}"]`];
|
||||
bundled = await runOffThread(
|
||||
{ kind: "parts", html: bundled, ignore },
|
||||
rootDeadline,
|
||||
mainCompositionPath,
|
||||
);
|
||||
if ((await createProjectSignatureAsync(project.dir)) === signature) {
|
||||
rememberPreview(builtKey, bundled);
|
||||
if (!capture) adapter.previewDocuments?.write(builtKey, bundled);
|
||||
@@ -588,6 +611,7 @@ export function registerPreviewRoutes(
|
||||
return bundled;
|
||||
} catch (error) {
|
||||
if (isCompositionTooLargeError(error)) return previewRefusalPage(error.message);
|
||||
console.warn("[Studio] preview build failed, building from the saved file:", error);
|
||||
// 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);
|
||||
|
||||
Reference in New Issue
Block a user