diff --git a/packages/studio-server/src/routes/preview.noPathTween.test.ts b/packages/studio-server/src/routes/preview.noPathTween.test.ts index a5cc851d61..c19237e45c 100644 --- a/packages/studio-server/src/routes/preview.noPathTween.test.ts +++ b/packages/studio-server/src/routes/preview.noPathTween.test.ts @@ -11,6 +11,8 @@ import { withPreviewRuntime, } from "./preview"; +type ScriptFiles = NonNullable[3]>; + const GSAP_FILE = "/*! GSAP 3.12.5 */ window.gsap = { timeline: function () {} };"; const PLAIN_TWEEN = ''; const LATE_PATH_TWEEN = @@ -116,6 +118,104 @@ describe("the preview builder's proof that no script can tween along a path", () }); }); +describe("the script scan's bounds", () => { + const tags = (srcs: string[]) => srcs.map((src) => ``).join(""); + const counting = (read: ScriptFiles["read"]) => { + const calls = { resolves: 0, reads: [] as string[] }; + const files: ScriptFiles = { + resolve: async (base, rel) => (calls.resolves++, join(base, rel)), + read: (file, signal) => (calls.reads.push(file), read(file, signal)), + }; + return { calls, files }; + }; + // As `readFile` does with its signal. + const untilAborted = (signal: AbortSignal) => + new Promise((_, reject) => + signal.addEventListener("abort", () => reject(signal.reason)), + ); + const scripts = (count: number) => + Object.fromEntries(Array.from({ length: count }, (_, i) => [`s${i}.js`, GSAP_FILE])); + + // fails without the fix: the scan resolved, stat'ed and read the one file once per tag. + it("answers false for a page with more script tags than it scans, reading nothing", async () => { + const { html, dir } = page(tags(Array(30_000).fill("gsap.min.js")), { + "gsap.min.js": GSAP_FILE, + }); + const { calls, files } = counting(async () => GSAP_FILE); + const answer = await provesNoPathTween(html, dir, Number.POSITIVE_INFINITY, files); + expect(calls.resolves).toBe(0); + expect(calls.reads).toHaveLength(0); + expect(answer).toBe(false); + }); + + // fails without the fix: each tag read its file again. + it("reads each script file once, however many tags and spellings name it", async () => { + const srcs = Array.from({ length: 40 }, (_, i) => ["a.js", "./a.js", "b.js", "c.js"][i % 4]!); + const { html, dir } = page(tags(srcs), { + "a.js": GSAP_FILE, + "b.js": GSAP_FILE, + "c.js": GSAP_FILE, + }); + const { calls, files } = counting(async () => GSAP_FILE); + expect(await provesNoPathTween(html, dir, Number.POSITIVE_INFINITY, files)).toBe(true); + expect(calls.reads.map((file) => file.slice(dir.length + 1)).sort()).toEqual([ + "a.js", + "b.js", + "c.js", + ]); + }); + + // fails without the fix: every tag's read started at once. + it("has at most 8 reads in flight", async () => { + const waiting: (() => void)[] = []; + let inFlight = 0; + let most = 0; + const { calls, files } = counting( + () => + new Promise((resolve) => { + most = Math.max(most, ++inFlight); + waiting.push(() => (inFlight--, resolve(GSAP_FILE))); + }), + ); + const { html, dir } = page(tags(Object.keys(scripts(20))), scripts(20)); + let answer: boolean | undefined; + void provesNoPathTween(html, dir, Number.POSITIVE_INFINITY, files).then((a) => (answer = a)); + while (answer === undefined) { + waiting.shift()?.(); + await new Promise(setImmediate); + } + expect(answer).toBe(true); + expect(calls.reads).toHaveLength(20); + expect(most).toBeLessThanOrEqual(8); + }); + + // fails without the fix: a read went on after the scan gave up on it. + it("aborts a read still in flight when the scan's time runs out", async () => { + const signals: (AbortSignal | undefined)[] = []; + const { files } = counting((_, signal) => { + signals.push(signal); + return untilAborted(signal); + }); + const { html, dir } = page(tags(["gsap.min.js"]), { "gsap.min.js": GSAP_FILE }); + expect(await provesNoPathTween(html, dir, performance.now() + 100, files)).toBe(false); + expect(signals).toHaveLength(1); + expect(signals[0]?.aborted).toBe(true); + }); + + // fails without the fix: every script was read even after one named a path. + it("starts no read after a script names a path, and aborts the ones in flight", async () => { + const signals: AbortSignal[] = []; + const { calls, files } = counting((file, signal) => { + signals.push(signal); + return file.endsWith("s0.js") ? Promise.resolve(LATE_PATH_TWEEN) : untilAborted(signal); + }); + const { html, dir } = page(tags(Object.keys(scripts(20))), scripts(20)); + expect(await provesNoPathTween(html, dir, Number.POSITIVE_INFINITY, files)).toBe(false); + expect(calls.reads.length).toBeLessThanOrEqual(8); + expect(signals.every((signal) => signal.aborted)).toBe(true); + }); +}); + describe("the preview's path-free mark", () => { it("is set only when the builder proved the page path-free", () => { const { html, dir } = page(""); diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.ts index ae93aca6e4..7d9f3c4d8b 100644 --- a/packages/studio-server/src/routes/preview.ts +++ b/packages/studio-server/src/routes/preview.ts @@ -209,45 +209,49 @@ const PROJECT_PREVIEW_BASE = const MAX_READ_SCRIPT_BYTES = 4 * 1024 * 1024; const SCRIPT_SCAN_MS = 1000; +// A page with more script tags than this is unsure, and unsure already means it preloads the plugin. +const MAX_SCANNED_SCRIPTS = 64; +const SCRIPT_READS_IN_FLIGHT = 8; /** How the scan reaches a project's files: both off the event loop. */ interface ScriptFiles { resolve: (base: string, relativePath: string) => Promise; - read: (file: string) => Promise; + read: (file: string, signal: AbortSignal) => Promise; } const projectFiles: ScriptFiles = { resolve: resolveExistingProjectFileOff, - read: (file) => readFile(file, "utf-8"), + read: (file, signal) => readFile(file, { encoding: "utf-8", signal }), }; -async function projectScriptNamesNoPath( - src: string, - projectDir: string, - files: ScriptFiles, -): Promise { - if (/^(?:[a-z][\w+.-]*:|\/)/i.test(src)) return false; - try { - const file = await files.resolve(projectDir, decodeURIComponent(src.split(/[?#]/)[0]!)); - if (file === null) return false; - const info = await statFile(file); - if (!info.isFile() || info.size > MAX_READ_SCRIPT_BYTES) return false; - return !namesMotionPath(await files.read(file)); - } catch { - return false; - } +async function fileNamesNoPath(file: string, files: ScriptFiles, signal: AbortSignal) { + const info = await statFile(file); + if (!info.isFile() || info.size > MAX_READ_SCRIPT_BYTES || signal.aborted) return false; + return !namesMotionPath(await files.read(file, signal)); } -async function scriptCannotTweenAlongPath( - tag: string, - projectDir: string, - files: ScriptFiles, -): Promise { +function scriptTagAnswer(tag: string): boolean | { src: string } { if (tag.includes(RUNTIME_BOOTSTRAP_ATTR)) return true; if (/\stype\s*=\s*["']?module\b/i.test(tag)) return false; const match = SCRIPT_SRC_ATTR.exec(tag); if (!match) return true; const src = (match[1] ?? match[2] ?? match[3] ?? "").replace(/&/gi, "&"); - return GSAP_ON_ITS_CDN.test(src) || projectScriptNamesNoPath(src, projectDir, files); + if (GSAP_ON_ITS_CDN.test(src)) return true; + return /^(?:[a-z][\w+.-]*:|\/)/i.test(src) ? false : { src }; +} + +async function inPool( + items: Iterable, + size: number, + signal: AbortSignal, + work: (item: T) => Promise, +): Promise { + const pending = items[Symbol.iterator](); + const worker = async () => { + for (let next = pending.next(); !next.done && !signal.aborted; next = pending.next()) { + await work(next.value); + } + }; + await Promise.all(Array.from({ length: size }, worker)); } /** True only when no script the page loads can tween along a path: the page's text and each project script it loads @@ -265,14 +269,38 @@ export async function provesNoPathTween( const now = performance.now(); const deadline = now + Math.min(SCRIPT_SCAN_MS, (requestDeadline - now) / 2); if (deadline <= now) return false; - const scripts = findStartTags(html, "script").map((start) => - scriptCannotTweenAlongPath(html.slice(start, html.indexOf(">", start) + 1), projectDir, files), - ); + const tags = findStartTags(html, "script"); + if (tags.length > MAX_SCANNED_SCRIPTS) return false; + const srcs = new Set(); + for (const start of tags) { + const answer = scriptTagAnswer(html.slice(start, html.indexOf(">", start) + 1)); + if (answer === false) return false; + if (answer !== true) srcs.add(answer.src); + } + // Aborted when a script names a path or the scan ends, so it stops every read it started. + const scan = new AbortController(); + const byFile = new Map>(); + const check = async (src: string) => { + const file = await files.resolve(projectDir, decodeURIComponent(src.split(/[?#]/)[0]!)); + if (file === null) return false; + let answer = byFile.get(file); + if (!answer) byFile.set(file, (answer = fileNamesNoPath(file, files, scan.signal))); + return answer; + }; + const stopUnlessNoPath = async (src: string) => { + if (!(await check(src).catch(() => false))) scan.abort(); + }; try { - const answers = await withinDeadline(Promise.all(scripts), deadline, "scripts"); - return answers.every(Boolean); + await withinDeadline( + inPool(srcs, SCRIPT_READS_IN_FLIGHT, scan.signal, stopUnlessNoPath), + deadline, + "scripts", + ); + return !scan.signal.aborted; } catch { return false; + } finally { + scan.abort(); } }