diff --git a/packages/studio-server/src/helpers/previewReads.ts b/packages/studio-server/src/helpers/previewReads.ts index 52de4eedc2..d75c9b56bd 100644 --- a/packages/studio-server/src/helpers/previewReads.ts +++ b/packages/studio-server/src/helpers/previewReads.ts @@ -75,9 +75,12 @@ function walkNow(walk: LinkWalk): string[] { return step.value; } -async function walkOff(walk: LinkWalk): Promise { +async function walkOff( + walk: LinkWalk, + readLink: (path: string) => Promise, +): Promise { let step = walk.next(); - while (!step.done) step = walk.next(await readLinkOff(step.value)); + while (!step.done) step = walk.next(await readLink(step.value)); return step.value; } @@ -99,13 +102,32 @@ export function recordPreviewRead(projectDir: string, filePath: string): void { remember(realProject, read, walkNow(linksOnTheWay(read))); } -/** `recordPreviewRead` for a route that reads its project off the event loop. */ -export async function recordPreviewReadOff(projectDir: string, filePath: string): Promise { - if (filePath.length > MAX_PREVIEW_PATH_LENGTH) return; - const realProject = await realFilePathOff(resolve(projectDir)); - const read = inReal(realProject, projectDir, filePath); - if (read.length > MAX_PREVIEW_PATH_LENGTH) return; - remember(realProject, read, await walkOff(linksOnTheWay(read))); +/** `recordPreviewRead` for each of `filePaths`, off the event loop; a folder they share is read once per call. */ +export async function recordPreviewReadsOff( + projectDir: string, + filePaths: Iterable, +): Promise { + const realProject = await realFilePathOff(resolve(projectDir)).catch(() => + realFilePath(resolve(projectDir)), + ); + const links = new Map>(); + const readLinkOnce = (path: string) => { + let target = links.get(path); + if (!target) links.set(path, (target = readLinkOff(path))); + return target; + }; + const pending = filePaths[Symbol.iterator](); + const recordNext = async () => { + for (let next = pending.next(); !next.done; next = pending.next()) { + const filePath = next.value; + if (filePath.length > MAX_PREVIEW_PATH_LENGTH) continue; + const read = inReal(realProject, projectDir, filePath); + if (read.length > MAX_PREVIEW_PATH_LENGTH) continue; + remember(realProject, read, await walkOff(linksOnTheWay(read), readLinkOnce)); + } + }; + // Enough walks in flight to keep the fs thread pool (4 threads by default) busy. + await Promise.all(Array.from({ length: 16 }, recordNext)); } export function previewReferences(html: string): Set { diff --git a/packages/studio-server/src/routes/preview.readsOffLoop.test.ts b/packages/studio-server/src/routes/preview.readsOffLoop.test.ts new file mode 100644 index 0000000000..fc28400f1a --- /dev/null +++ b/packages/studio-server/src/routes/preview.readsOffLoop.test.ts @@ -0,0 +1,125 @@ +// @vitest-environment node +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { monitorEventLoopDelay } from "node:perf_hooks"; +import { Hono } from "hono"; +import { afterEach, expect, it } from "vitest"; +import { affectsPreview } from "../helpers/previewReads"; +import type { StudioApiAdapter } from "../types"; +import { registerPreviewRoutes } from "./preview"; + +const FILES = 20_000; +let root = ""; +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const adapter = (dir: string, bundle: StudioApiAdapter["bundle"]): StudioApiAdapter => ({ + listProjects: () => [], + resolveProject: async (id: string) => ({ id, dir }), + bundle, + lint: async () => ({ findings: [] }), + runtimeUrl: "/api/runtime.js", + rendersDir: () => "/tmp/renders", + startRender: () => ({ + id: "job-1", + status: "rendering", + progress: 0, + outputPath: "/tmp/out.mp4", + }), +}); + +// The histogram has no sample for work that starts in the tick it was enabled in, so wait for one first. +async function longestHoldMs(work: () => Promise): Promise { + const delay = monitorEventLoopDelay({ resolution: 10 }); + delay.enable(); + while (delay.count === 0) await new Promise(setImmediate); + await work(); + const seen = delay.count; + while (delay.count === seen) await new Promise(setImmediate); + delay.disable(); + return delay.max / 1e6; +} + +const pageNaming = (files: string[]) => + `${files.map((file) => ``).join("")}`; + +// fails without the fix: the build walked each of its 40,000 reads with blocking readlinks (a 1.7 s hold). +it("builds a preview of a page naming 20,000 media files without holding the event loop", async () => { + root = mkdtempSync(join(tmpdir(), "preview-reads-")); + // In a linked library, which the project's signature does not list, so the build's own reads are what is timed. + const library = join(root, "library"); + const projectDir = join(root, "project"); + mkdirSync(library); + mkdirSync(projectDir); + symlinkSync(library, join(projectDir, "media"), "junction"); + const files = Array.from({ length: FILES }, (_, i) => `media/clip-${i}.png`); + for (let i = 0; i < FILES; i++) writeFileSync(join(library, `clip-${i}.png`), ""); + const html = pageNaming(files); + writeFileSync(join(projectDir, "index.html"), html); + const app = new Hono(); + registerPreviewRoutes( + app, + adapter(projectDir, async (dir, options) => { + for (const file of files) options?.onRead?.(join(dir, file)); + return html; + }), + ); + + let status = 0; + const hold = await longestHoldMs(async () => { + status = (await app.request("http://localhost/projects/demo/preview")).status; + }); + + expect(status).toBe(200); + expect(hold).toBeLessThan(200); + expect(affectsPreview(projectDir, join(library, `clip-${FILES - 1}.png`))).toBe(true); +}); + +// fails without the fix: the build failed and the sub-composition route answered a server error. +it.skipIf(process.platform === "win32")( + "still answers when the project folder's real path cannot be resolved", + async () => { + root = mkdtempSync(join(tmpdir(), "preview-reads-")); + const projectDir = join(root, "loop"); + symlinkSync("loop", projectDir); + const html = pageNaming(["media/a.png"]); + const app = new Hono(); + registerPreviewRoutes( + app, + adapter(projectDir, async () => html), + ); + + expect((await app.request("http://localhost/projects/demo/preview")).status).toBe(200); + expect( + (await app.request("http://localhost/projects/demo/preview/comp/scene.html")).status, + ).toBe(404); + }, +); + +it.skipIf(process.platform === "win32")( + "counts a change behind a symlinked folder the build read through", + async () => { + const projectDir = (root = realpathSync(mkdtempSync(join(tmpdir(), "preview-reads-")))); + mkdirSync(join(projectDir, "shared", "clips"), { recursive: true }); + writeFileSync(join(projectDir, "shared", "clips", "a.png"), ""); + writeFileSync(join(projectDir, "shared", "clips", "b.png"), ""); + symlinkSync("shared/clips", join(projectDir, "media")); + const html = pageNaming(["media/a.png"]); + writeFileSync(join(projectDir, "index.html"), html); + const app = new Hono(); + registerPreviewRoutes( + app, + adapter(projectDir, async (dir, options) => { + options?.onRead?.(join(dir, "media", "b.png")); + return html; + }), + ); + + expect((await app.request("http://localhost/projects/demo/preview")).status).toBe(200); + + expect(affectsPreview(projectDir, "media")).toBe(true); + expect(affectsPreview(projectDir, "shared/clips/a.png")).toBe(true); + expect(affectsPreview(projectDir, "shared/clips/b.png")).toBe(true); + expect(affectsPreview(projectDir, "shared/clips/c.png")).toBe(false); + }, +); diff --git a/packages/studio-server/src/routes/preview.recordClosed.test.ts b/packages/studio-server/src/routes/preview.recordClosed.test.ts index 46c1671ca0..d7b00575f8 100644 --- a/packages/studio-server/src/routes/preview.recordClosed.test.ts +++ b/packages/studio-server/src/routes/preview.recordClosed.test.ts @@ -8,7 +8,7 @@ import type { StudioApiAdapter } from "../types"; // A path that stops resolving between the private-file check and the read's record (a link swapped for a loop). vi.mock("../helpers/previewReads.js", async (importOriginal) => ({ ...(await importOriginal()), - recordPreviewReadOff: () => Promise.reject(Object.assign(new Error("ELOOP"), { code: "ELOOP" })), + recordPreviewReadsOff: () => Promise.reject(Object.assign(new Error("ELOOP"), { code: "ELOOP" })), })); const { createStudioApi } = await import("../createStudioApi"); diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.ts index de6f8aa71f..ae93aca6e4 100644 --- a/packages/studio-server/src/routes/preview.ts +++ b/packages/studio-server/src/routes/preview.ts @@ -86,7 +86,7 @@ import { settledFileTag } from "../helpers/fileVersion.js"; import { recordPreviewBuilt, recordPreviewRead, - recordPreviewReadOff, + recordPreviewReadsOff, } from "../helpers/previewReads.js"; import { isVariablesPayload, VARIABLES_PAYLOAD_ERROR } from "../helpers/variablesPayload.js"; import { injectPreviewVariables } from "../helpers/previewVariables.js"; @@ -631,11 +631,14 @@ export function registerPreviewRoutes( const diskMain = resolveProjectMainHtml(project.dir, project.id); try { - let bundled = await adapter.bundle(project.dir, { - stampHfIds: true, - onRead: (filePath) => recordPreviewRead(project.dir, filePath), - privateFiles: "studio", - }); + const reads: string[] = []; + let bundled = await adapter + .bundle(project.dir, { + stampHfIds: true, + onRead: (filePath) => reads.push(filePath), + privateFiles: "studio", + }) + .finally(() => recordPreviewReadsOff(project.dir, reads)); let mainCompositionPath = "index.html"; if (!bundled) { if (!diskMain) return null; @@ -650,7 +653,7 @@ export function registerPreviewRoutes( mainCompositionPath, ); bundled = based.html; - for (const path of based.references) recordPreviewRead(project.dir, path); + await recordPreviewReadsOff(project.dir, based.references); recordPreviewBuilt(project.dir); // The passes that parse the page run on the build worker (a capture page builds while a film plays); the @@ -802,9 +805,8 @@ export function registerPreviewRoutes( project.dir, requestSubPath(c.req.url, "projects/:id/preview/comp"), ); - if (compFile) recordPreviewRead(project.dir, compFile); // The sub-composition document takes its head from the root. - recordPreviewRead(project.dir, "index.html"); + await recordPreviewReadsOff(project.dir, compFile ? [compFile, "index.html"] : ["index.html"]); if (!compFile || !existsSync(compFile) || !statSync(compFile).isFile()) { return c.text("not found", 404); } @@ -837,7 +839,7 @@ export function registerPreviewRoutes( ); 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); + await recordPreviewReadsOff(project.dir, built.references); const transformed = await withinDeadline( transformPreviewHtml(built.html, adapter, project, compPath), deadline, @@ -888,7 +890,7 @@ export function registerPreviewRoutes( if (!file || (await isPrivateProjectFileOff(project.dir, file))) { return c.text("not found", 404); } - const recorded = await recordPreviewReadOff(project.dir, file).then( + const recorded = await recordPreviewReadsOff(project.dir, [file]).then( () => true, () => false, );