diff --git a/packages/studio-server/src/helpers/previewJobs.ts b/packages/studio-server/src/helpers/previewJobs.ts new file mode 100644 index 0000000000..89136e48b6 --- /dev/null +++ b/packages/studio-server/src/helpers/previewJobs.ts @@ -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; + } +} diff --git a/packages/studio-server/src/helpers/previewReads.ts b/packages/studio-server/src/helpers/previewReads.ts index 122cfb917f..102eae1b76 100644 --- a/packages/studio-server/src/helpers/previewReads.ts +++ b/packages/studio-server/src/helpers/previewReads.ts @@ -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 { const named = new Set(); const add = (reference: string) => { diff --git a/packages/studio-server/src/helpers/subCompositionBuild.ts b/packages/studio-server/src/helpers/subCompositionBuild.ts index 655ecc00cd..60fc370953 100644 --- a/packages/studio-server/src/helpers/subCompositionBuild.ts +++ b/packages/studio-server/src/helpers/subCompositionBuild.ts @@ -24,10 +24,25 @@ export interface FinishJob { variables?: Record; } -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 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; diff --git a/packages/studio-server/src/helpers/subCompositionWorker.ts b/packages/studio-server/src/helpers/subCompositionWorker.ts index fb7377c4e5..52b0a6c7cd 100644 --- a/packages/studio-server/src/helpers/subCompositionWorker.ts +++ b/packages/studio-server/src/helpers/subCompositionWorker.ts @@ -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) }); } diff --git a/packages/studio-server/src/routes/preview.parseCount.test.ts b/packages/studio-server/src/routes/preview.parseCount.test.ts index 086d3aaeff..ff8bc43ff8 100644 --- a/packages/studio-server/src/routes/preview.parseCount.test.ts +++ b/packages/studio-server/src/routes/preview.parseCount.test.ts @@ -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()), + 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, or scene parts", async () => { diff --git a/packages/studio-server/src/routes/preview.rootOffThread.test.ts b/packages/studio-server/src/routes/preview.rootOffThread.test.ts new file mode 100644 index 0000000000..38d4612eeb --- /dev/null +++ b/packages/studio-server/src/routes/preview.rootOffThread.test.ts @@ -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 = + (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(); + return { ...real, parseHTML: counted("parseHTML", real.parseHTML as (html: string) => unknown) }; +}); +vi.mock("@hyperframes/parsers/hf-ids", async (actual) => { + const real = await actual(); + return { ...real, ensureHfIds: counted("ensureHfIds", real.ensureHfIds) }; +}); +vi.mock("@hyperframes/core/compiler", async (actual) => { + const real = await actual(); + 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) => ``, +).join(""); +const page = `
${shapes}

Hi

`; +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(/]*data-hf-id="[^"]+"[^>]*>Hi<\/p>/); + expect(onThread.passes).toEqual([]); + } +}, 120_000); diff --git a/packages/studio-server/src/routes/preview.test.ts b/packages/studio-server/src/routes/preview.test.ts index 0f04f11ebb..2e4f91cf2e 100644 --- a/packages/studio-server/src/routes/preview.test.ts +++ b/packages/studio-server/src/routes/preview.test.ts @@ -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(() => { diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.ts index f6c3ae6f7a..ce711716c1 100644 --- a/packages/studio-server/src/routes/preview.ts +++ b/packages/studio-server/src/routes/preview.ts @@ -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, ``); @@ -559,20 +555,42 @@ export function registerPreviewRoutes( mainCompositionPath = diskMain.compositionPath; } // 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);