fix(studio-server): a preview file request no longer waits on a silent drive on the event loop (#8254)

* test(studio-server): a preview file request on a silent drive asks it nothing on the event loop

* fix(studio-server): a preview file request reads its project off the event loop

* ci(studio-server): refuse a new synchronous fs call in Studio's routes and history engine

* fix(studio-server): a preview file request and a miss stay off the event loop to the end

* test(studio-server): a shared still's remake no longer depends on busy requests' slot order

* fix(ci): the studio-server sync fs gate counts every sync call node:fs has, globSync included
This commit is contained in:
Miguel Ángel
2026-11-21 09:03:14 +00:00
committed by GitHub
parent ba81f67930
commit 7cb605c787
12 changed files with 382 additions and 23 deletions
+1
View File
@@ -357,6 +357,7 @@ jobs:
if-no-files-found: error
retention-days: 7
- run: bun run check:cli-lazy-deps
- run: bun run check:studio-server-sync-fs
# The shards need only the built CLI; building it apart keeps them from waiting on Build's packing checks.
edit-accuracy-cli:
+3
View File
@@ -41,6 +41,9 @@ pre-commit:
- name: cli-process-ownership
glob: "packages/cli/src/**/*.ts"
run: bun run check:cli-process-ownership
- name: studio-server-sync-fs
glob: "packages/studio-server/src/{routes,history}/**/*.ts"
run: bun run check:studio-server-sync-fs
- name: largefiles
# Rejects staged binaries over the limit that are not LFS pointers; see
# the script header. CI runs the same script with --range.
+2 -1
View File
@@ -42,6 +42,7 @@
"check:workspace-contracts": "node scripts/check-workspace-contracts.mjs",
"check:package-cycles": "node scripts/check-package-cycles.mjs",
"check:cli-process-ownership": "node scripts/check-cli-process-ownership.mjs",
"check:studio-server-sync-fs": "node scripts/check-studio-server-sync-fs.mjs",
"check:cli-lazy-deps": "node scripts/check-cli-lazy-deps.mjs",
"check:studio-copy-dashes": "node scripts/check-studio-copy-dashes.mjs",
"check:registry-innerhtml": "node scripts/check-registry-innerhtml.mjs",
@@ -57,7 +58,7 @@
"player:perf": "bun run --filter @hyperframes/player perf",
"format:check": "oxfmt --check .",
"knip": "knip",
"test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-committed-keys.test.mjs scripts/check-symlinks.test.mjs scripts/upload-docs-images.test.mjs scripts/check-registry-set-delta.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-comment-citations.test.mjs scripts/comments-workflow.test.mjs scripts/comment-ratchet.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-svg-sanitize-parity.test.mjs scripts/check-media-use-svg-sanitize-generated.test.mjs scripts/check-media-use-audio-carve-generated.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-cli-lazy-deps.test.mjs scripts/file-url-paths.test.mjs scripts/check-studio-copy-dashes.test.mjs scripts/check-large-files.test.mjs scripts/check-registry-innerhtml.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/clawhub-sync.test.mjs scripts/clawhub-unlist-retired.test.mjs scripts/publish-workflow.test.mjs scripts/release-lambda-assets.test.mjs scripts/publish-main-only-workflows.test.mjs scripts/mcp-registry-watch.test.mjs scripts/pr-edit-concurrency.test.mjs scripts/merge-queue-workflows.test.mjs scripts/ci-cache-workflows.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/check-edit-accuracy-filter.test.mjs scripts/edit-accuracy-retry.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/backfill-block-previews.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/registry-cdn-pins.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/rewrite-relative-import-extensions.test.mjs scripts/lint-skills.test.mjs scripts/check-core-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-publication.test.mjs scripts/ci/resolve-workflow-pr.test.mjs scripts/lefthook-order.test.mjs scripts/inline-gsap.test.mjs scripts/ci/flake-gate.test.mjs scripts/ci/motion-blur-nightly-report.test.mjs scripts/ci/base-file.test.mjs scripts/ci/release-only-diff.test.mjs scripts/check-catalog-source-pr.test.mjs scripts/generate-registry-items.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-theme-fallbacks.test.ts scripts/registry-skill-files.test.ts scripts/creator-editing-capabilities.test.mjs scripts/generate-catalog-previews.test.ts scripts/registry-primitive-payloads.test.ts registry/components/pan-stations/pan-stations.test.mjs registry/components/filmed-screen/filmed-screen.test.mjs registry/components/echo-smear/echo-smear.test.mjs registry/examples/path-traced-3d/source/path-traced-3d.test.mjs && vitest run scripts/catalog/ scripts/contrastRatchet.test.ts scripts/generate-catalog-payloads.test.ts",
"test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-committed-keys.test.mjs scripts/check-symlinks.test.mjs scripts/upload-docs-images.test.mjs scripts/check-registry-set-delta.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-comment-citations.test.mjs scripts/comments-workflow.test.mjs scripts/comment-ratchet.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-svg-sanitize-parity.test.mjs scripts/check-media-use-svg-sanitize-generated.test.mjs scripts/check-media-use-audio-carve-generated.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-studio-server-sync-fs.test.mjs scripts/check-cli-lazy-deps.test.mjs scripts/file-url-paths.test.mjs scripts/check-studio-copy-dashes.test.mjs scripts/check-large-files.test.mjs scripts/check-registry-innerhtml.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/clawhub-sync.test.mjs scripts/clawhub-unlist-retired.test.mjs scripts/publish-workflow.test.mjs scripts/release-lambda-assets.test.mjs scripts/publish-main-only-workflows.test.mjs scripts/mcp-registry-watch.test.mjs scripts/pr-edit-concurrency.test.mjs scripts/merge-queue-workflows.test.mjs scripts/ci-cache-workflows.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/check-edit-accuracy-filter.test.mjs scripts/edit-accuracy-retry.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/backfill-block-previews.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/registry-cdn-pins.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/rewrite-relative-import-extensions.test.mjs scripts/lint-skills.test.mjs scripts/check-core-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-publication.test.mjs scripts/ci/resolve-workflow-pr.test.mjs scripts/lefthook-order.test.mjs scripts/inline-gsap.test.mjs scripts/ci/flake-gate.test.mjs scripts/ci/motion-blur-nightly-report.test.mjs scripts/ci/base-file.test.mjs scripts/ci/release-only-diff.test.mjs scripts/check-catalog-source-pr.test.mjs scripts/generate-registry-items.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-theme-fallbacks.test.ts scripts/registry-skill-files.test.ts scripts/creator-editing-capabilities.test.mjs scripts/generate-catalog-previews.test.ts scripts/registry-primitive-payloads.test.ts registry/components/pan-stations/pan-stations.test.mjs registry/components/filmed-screen/filmed-screen.test.mjs registry/components/echo-smear/echo-smear.test.mjs registry/examples/path-traced-3d/source/path-traced-3d.test.mjs && vitest run scripts/catalog/ scripts/contrastRatchet.test.ts scripts/generate-catalog-payloads.test.ts",
"typecheck:scripts": "tsc --noEmit -p scripts/tsconfig.json",
"test:skills": "HYPERFRAMES_MEDIA_HOME_REQUIRED=1 node --import ./packages/cli/scripts/test-home.mjs --test 'skills/**/*.test.mjs' 'packages/cli/src/media-use/**/*.test.mjs'",
"generate:previews": "tsx scripts/generate-template-previews.ts",
@@ -26,7 +26,8 @@ import { registerMediaRoutes } from "./routes/media.js";
import { registerGlobalAssetRoutes } from "./routes/globalAssets.js";
import { registerHistoryRoutes } from "./routes/history.js";
import { replaceWithProjectDirMissing } from "./helpers/projectDirMissing.js";
import { folderGone, isProjectRootMissing } from "./helpers/safePath.js";
import { isProjectRootMissing } from "./helpers/safePath.js";
import { folderGoneOff } from "./helpers/projectDisk.js";
import {
PREVIEW_ALLOWED_HOSTS_ENV,
documentFromAnotherSite,
@@ -254,7 +255,7 @@ export function createStudioApi(adapter: StudioApiAdapter, options: StudioApiOpt
() => undefined,
);
await next();
if (c.res.status >= 403 && dirBeforeRoute && folderGone(dirBeforeRoute))
if (c.res.status >= 403 && dirBeforeRoute && (await folderGoneOff(dirBeforeRoute)))
replaceWithProjectDirMissing(c, hostHeaders);
});
api.use("/projects/:id/*", async function forgetSignatureAfterWrite(c, next) {
@@ -1,8 +1,10 @@
import { readlinkSync } from "node:fs";
import { readlink } from "node:fs/promises";
import { dirname, join, parse, relative, resolve } from "node:path";
import { parseHTML } from "linkedom";
import { STUDIO_SIGNATURE_MANIFEST_PATHS } from "./projectSignature.js";
import { realFilePath } from "./safePath.js";
import { realFilePathOff } from "./projectDisk.js";
const ALWAYS_AFFECTS = ["hyperframes.json", ...STUDIO_SIGNATURE_MANIFEST_PATHS];
// A malformed inline URL must not turn ancestor tracking into an image-sized path walk.
@@ -21,8 +23,10 @@ const pathKey =
const readsByProject = new Map<string, Set<string>>();
const builtProjects = new Set<string>();
const projectKey = (projectDir: string) => pathKey(realFilePath(resolve(projectDir)));
const inReal = (realProject: string, projectDir: string, path: string) =>
join(realProject, relative(resolve(projectDir), resolve(projectDir, path)));
const inRealProject = (projectDir: string, path: string) =>
join(realFilePath(resolve(projectDir)), relative(resolve(projectDir), resolve(projectDir, path)));
inReal(realFilePath(resolve(projectDir)), projectDir, path);
const readLink = (path: string): string | null => {
try {
@@ -31,9 +35,13 @@ const readLink = (path: string): string | null => {
return null;
}
};
const readLinkOff = (path: string): Promise<string | null> => readlink(path).catch(() => null);
// Walks `path` as the OS does, returning every link it passes and where it ends up.
function linksOnTheWay(path: string): string[] {
type LinkWalk = Generator<string, string[], string | null>;
// Walks `path` as the OS does, returning every link it passes and where it ends up. It yields each path whose link
// target it needs, so one walk serves both a blocking and an off-loop reader.
function* linksOnTheWay(path: string): LinkWalk {
const passed: string[] = [];
let at = parse(path).root;
let rest = path.slice(at.length).split(/[\\/]+/);
@@ -46,7 +54,7 @@ function linksOnTheWay(path: string): string[] {
}
const next = join(at, part);
if (next.length > MAX_PREVIEW_PATH_LENGTH) return passed;
const target = hops < 40 ? readLink(next) : null;
const target = hops < 40 ? yield next : null;
if (target === null) {
at = next;
continue;
@@ -61,17 +69,43 @@ function linksOnTheWay(path: string): string[] {
return passed;
}
function walkNow(walk: LinkWalk): string[] {
let step = walk.next();
while (!step.done) step = walk.next(readLink(step.value));
return step.value;
}
async function walkOff(walk: LinkWalk): Promise<string[]> {
let step = walk.next();
while (!step.done) step = walk.next(await readLinkOff(step.value));
return step.value;
}
function remember(realProject: string, read: string, links: string[]): void {
const key = pathKey(realProject);
let reads = readsByProject.get(key);
if (!reads) readsByProject.set(key, (reads = new Set()));
for (const found of [read, ...links]) {
for (let path = pathKey(found); !reads.has(path); path = dirname(path)) reads.add(path);
}
}
// A link's target can be created or retargeted later, so every read resolves it again.
export function recordPreviewRead(projectDir: string, filePath: string): void {
if (filePath.length > MAX_PREVIEW_PATH_LENGTH) return;
const key = projectKey(projectDir);
let reads = readsByProject.get(key);
if (!reads) readsByProject.set(key, (reads = new Set()));
const read = inRealProject(projectDir, filePath);
const realProject = realFilePath(resolve(projectDir));
const read = inReal(realProject, projectDir, filePath);
if (read.length > MAX_PREVIEW_PATH_LENGTH) return;
for (const found of [read, ...linksOnTheWay(read)]) {
for (let path = pathKey(found); !reads.has(path); path = dirname(path)) reads.add(path);
}
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<void> {
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)));
}
export function previewReferences(html: string): Set<string> {
@@ -0,0 +1,36 @@
import type { Stats } from "node:fs";
import { realpath, stat } from "node:fs/promises";
import { basename, dirname, join, relative, sep } from "node:path";
import { isPrivateProjectPath } from "./safePath.js";
// Null for any failure, as `existsSync` answers false: an unreadable folder stays "not found", never a refusal.
export const statOrNull = (path: string): Promise<Stats | null> => stat(path).catch(() => null);
export const folderGoneOff = (dir: string): Promise<boolean> =>
stat(dir).then(
() => false,
(error: NodeJS.ErrnoException) => error.code === "ENOENT" || error.code === "ENOTDIR",
);
/** The real path; for a path not there (yet, or any more), the nearest existing folder's real path plus the rest. */
export async function realFilePathOff(filePath: string): Promise<string> {
try {
return await realpath(filePath);
} catch {
const dir = dirname(filePath);
return dir === filePath ? filePath : join(await realFilePathOff(dir), basename(filePath));
}
}
export async function isPrivateProjectFileOff(
projectDir: string,
filePath: string,
): Promise<boolean> {
const rel = (from: string, to: string) => relative(from, to).split(sep).join("/");
if (isPrivateProjectPath(rel(projectDir, filePath))) return true;
const [realDir, realFile] = await Promise.all([
realFilePathOff(projectDir),
realFilePathOff(filePath),
]);
return isPrivateProjectPath(rel(realDir, realFile));
}
@@ -0,0 +1,148 @@
// @vitest-environment node
// A host runs these routes on its own event loop: a synchronous read of a folder whose drive stopped answering holds
// that loop, and with it every other request, for as long as the drive stays silent.
import { afterEach, expect, it, vi } from "vitest";
import fs, {
chmodSync,
mkdirSync,
mkdtempSync,
realpathSync,
rmSync,
writeFileSync,
} from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createStudioApi } from "../createStudioApi";
import type { StudioApiAdapter } from "../types";
const SYNC = [
"existsSync",
"statSync",
"lstatSync",
"realpathSync",
"readFileSync",
"readdirSync",
"readlinkSync",
"accessSync",
"openSync",
] as const;
const ASYNC = ["stat", "lstat", "realpath", "readFile", "readlink"] as const;
let projectDir = "";
const wake: (() => void)[] = [];
afterEach(() => {
for (const one of wake.splice(0)) one();
vi.restoreAllMocks();
syncBuiltinESMExports();
rmSync(projectDir, { recursive: true, force: true });
});
const adapter = (dir: string): StudioApiAdapter => ({
listProjects: () => [],
resolveProject: async (id: string) => ({ id, dir }),
bundle: async () => null,
lint: async () => ({ findings: [] }),
runtimeUrl: "/api/runtime.js",
rendersDir: () => "/tmp/renders",
startRender: () => ({
id: "job-1",
status: "rendering",
progress: 0,
outputPath: "/tmp/out.mp4",
}),
});
/** Every sync fs call on the project folder while watched; its fs/promises reads wait while it sleeps. */
function sleepyDrive(dir: string) {
const onDrive = (path: unknown) => String(path).startsWith(dir);
const drive = { watching: false, asleep: false, sync: [] as string[] };
const record = (name: string, path: unknown) => {
if (drive.watching && onDrive(path)) drive.sync.push(`${name} ${String(path)}`);
};
for (const name of SYNC) {
const real = fs[name] as (...args: unknown[]) => unknown;
vi.spyOn(fs, name).mockImplementation(((path: unknown, ...rest: unknown[]) => {
record(name, path);
return real(path, ...rest);
}) as never);
}
const native = fs.realpathSync.native as (...args: unknown[]) => unknown;
vi.spyOn(fs.realpathSync, "native").mockImplementation(((path: unknown, ...rest: unknown[]) => {
record("realpathSync.native", path);
return native(path, ...rest);
}) as never);
for (const name of ASYNC) {
const real = fs.promises[name] as (...args: unknown[]) => Promise<unknown>;
vi.spyOn(fs.promises, name).mockImplementation(((path: unknown, ...rest: unknown[]) =>
drive.asleep && onDrive(path)
? new Promise((done) => wake.push(() => done(real(path, ...rest))))
: real(path, ...rest)) as never);
}
syncBuiltinESMExports();
return drive;
}
/** Asks `path` while the drive sleeps, wakes it, and returns the answer once its body is read. */
async function askAsleep(path: string) {
const drive = sleepyDrive(projectDir);
const api = createStudioApi(adapter(projectDir));
drive.watching = drive.asleep = true;
let answered = false;
const pending = api.request(`http://localhost/projects/demo/preview/${path}`).then((res) => {
answered = true;
return res;
});
for (let turn = 0; turn < 5; turn++) await new Promise((next) => setImmediate(next));
const answeredAsleep = answered;
drive.asleep = false;
for (const one of wake.splice(0)) one();
const res = await pending;
const body = await res.text();
drive.watching = false;
return { status: res.status, body, sync: drive.sync, answeredAsleep };
}
const project = () => {
projectDir = realpathSync(mkdtempSync(join(tmpdir(), "hf-preview-asleep-")));
writeFileSync(join(projectDir, "notes.txt"), "hello");
};
// fails without the fix: the private-file check, the read tracker and the file's stat each made synchronous calls on
// the project folder.
it("a preview file request whose project's drive stops answering asks that drive nothing on the event loop", async () => {
project();
const asked = await askAsleep("notes.txt");
expect(asked.sync).toEqual([]);
expect(asked.answeredAsleep).toBe(false);
expect(asked.status).toBe(200);
expect(asked.body).toBe("hello");
});
it("a request for a file that is not there asks the silent drive nothing on the event loop either", async () => {
project();
const asked = await askAsleep("missing.txt");
expect(asked.sync).toEqual([]);
expect(asked.answeredAsleep).toBe(false);
expect(asked.status).toBe(404);
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"a file under a folder that refuses reads is still not found",
async () => {
project();
mkdirSync(join(projectDir, "locked"));
writeFileSync(join(projectDir, "locked", "a.txt"), "x");
chmodSync(join(projectDir, "locked"), 0o000);
try {
const res = await createStudioApi(adapter(projectDir)).request(
"http://localhost/projects/demo/preview/locked/a.txt",
);
expect(res.status).toBe(404);
expect(await res.text()).toBe("not found");
} finally {
chmodSync(join(projectDir, "locked"), 0o755);
}
},
);
@@ -2117,7 +2117,9 @@ describe("hf-proxy negotiation and media codec map injection (U3)", () => {
}
expect((await second).status).toBe(200);
for (const res of await Promise.all(busy)) expect(res.status).toBe(200);
expect(made).toEqual([1, 2, 3, 4, 10]);
// The four busy requests reach their slots in whichever order their file checks settle.
expect(made.slice(0, 4).sort()).toEqual([1, 2, 3, 4]);
expect(made.slice(4)).toEqual([10]);
});
it("honors If-None-Match on a repeat request with a 304, without re-invoking resolveProxy", async () => {
+14 -8
View File
@@ -1,6 +1,7 @@
import type { Hono } from "hono";
import { parseHTML } from "linkedom";
import { createReadStream, existsSync, readFileSync, statSync } from "node:fs";
import { readFile, stat as statFile } from "node:fs/promises";
import { stripSdrPngColourTags } from "@hyperframes/core/compiler/png-colour-tags";
import { Readable } from "node:stream";
import { join, resolve } from "node:path";
@@ -46,6 +47,7 @@ import {
projectRelativePath,
resolveWithinProject,
} from "../helpers/safePath.js";
import { isPrivateProjectFileOff, statOrNull } from "../helpers/projectDisk.js";
import { getMimeType } from "../helpers/mime.js";
import { serveWhileOpen } from "../helpers/servedFiles.js";
import { openRangeEnd } from "../helpers/mediaRange.js";
@@ -74,7 +76,11 @@ import {
} from "../helpers/studioMotionRenderScript.js";
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
import { settledFileTag } from "../helpers/fileVersion.js";
import { recordPreviewBuilt, recordPreviewRead } from "../helpers/previewReads.js";
import {
recordPreviewBuilt,
recordPreviewRead,
recordPreviewReadOff,
} from "../helpers/previewReads.js";
import { isVariablesPayload, VARIABLES_PAYLOAD_ERROR } from "../helpers/variablesPayload.js";
import { injectPreviewVariables } from "../helpers/previewVariables.js";
import {
@@ -776,11 +782,11 @@ export function registerPreviewRoutes(
// use resolveWithinProject because saves write their data-hf-id values.
const candidate = resolve(project.dir, subPath);
const file = isWithinProjectRoot(project.dir, candidate) ? candidate : null;
if (!file || isPrivateProjectFile(project.dir, file)) {
if (!file || (await isPrivateProjectFileOff(project.dir, file))) {
return c.text("not found", 404);
}
recordPreviewRead(project.dir, file);
const stat = existsSync(file) ? statSync(file) : null;
await recordPreviewReadOff(project.dir, file);
const stat = await statOrNull(file);
if (!stat?.isFile()) {
return c.text("not found", 404);
}
@@ -839,7 +845,7 @@ export function registerPreviewRoutes(
? ask()
: Promise.reject(err),
);
return new Response(readFileSync(still), {
return new Response(await readFile(still), {
headers: { "Content-Type": "image/jpeg", "Cache-Control": "private, max-age=3600" },
});
} catch (err) {
@@ -911,11 +917,11 @@ export function registerPreviewRoutes(
// 1KB slice of a multi-hundred-MB source must not readFileSync the whole
// file on each one. The full read also blocked the event loop, so every
// other Studio request (SSE, saves, the voice track) waited behind it.
const textBuffer = isText ? Buffer.from(readFileSync(file, "utf-8"), "utf-8") : null;
const textBuffer = isText ? Buffer.from(await readFile(file, "utf-8"), "utf-8") : null;
const heldBuffer =
textBuffer ??
(contentType === "image/png" ? stripSdrPngColourTags(readFileSync(file)) : null);
const totalSize = heldBuffer ? heldBuffer.length : statSync(servedPath).size;
(contentType === "image/png" ? stripSdrPngColourTags(await readFile(file)) : null);
const totalSize = heldBuffer ? heldBuffer.length : (await statFile(servedPath)).size;
const bodyFor = (start: number, end: number): BodyInit =>
heldBuffer
? new Uint8Array(heldBuffer.subarray(start, end + 1))
+70
View File
@@ -0,0 +1,70 @@
// Studio's routes and history engine run on the host's event loop (the CLI's preview server, the desktop app's main
// process): a synchronous read of a folder whose drive stopped answering holds that loop for as long as the drive is
// silent. Each file may only lose such calls, never gain one; its count is kept in the baseline beside this script.
import * as fs from "node:fs";
import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { join, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = join(import.meta.dirname, "..");
const AREAS = ["packages/studio-server/src/routes", "packages/studio-server/src/history"];
const BASELINE = join(import.meta.dirname, "studio-server-sync-fs-baseline.json");
// Every synchronous call the running node:fs has (`globSync` and any later one), `realpathSync.native` included.
const SYNC_NAMES = Object.keys(fs).filter((name) => name.endsWith("Sync"));
const SYNC_CALL = new RegExp(`\\b(?:${SYNC_NAMES.join("|")})(?:\\.native)?\\s*\\(`, "g");
/** How many synchronous fs calls `source` makes, comment lines aside. @param {string} source */
export function countSyncCalls(source) {
return source
.split("\n")
.filter((line) => !/^\s*(\/\/|\*|\/\*)/.test(line))
.reduce((sum, line) => sum + (line.match(SYNC_CALL)?.length ?? 0), 0);
}
/** @param {string} dir @returns {string[]} */
function sourceFiles(dir) {
return readdirSync(dir).flatMap((name) => {
const path = join(dir, name);
if (statSync(path).isDirectory()) return name === "__fixtures__" ? [] : sourceFiles(path);
return /\.ts$/.test(name) && !/\.test\.ts$/.test(name) ? [path] : [];
});
}
/** Each area file's count, by its path from the repo root. */
export function currentCounts(root = ROOT) {
return Object.fromEntries(
AREAS.flatMap((area) => sourceFiles(join(root, area)))
.map((path) => [
relative(root, path).split(sep).join("/"),
countSyncCalls(readFileSync(path, "utf8")),
])
.filter(([, count]) => count > 0)
.sort(([a], [b]) => a.localeCompare(b)),
);
}
/** The files that gained a synchronous fs call over the baseline. */
export function gained(current, baseline) {
return Object.entries(current)
.filter(([path, count]) => count > (baseline[path] ?? 0))
.map(
([path, count]) => `${path}: ${count} synchronous fs calls, ${baseline[path] ?? 0} allowed`,
);
}
function main() {
const current = currentCounts();
if (process.argv.includes("--write")) {
writeFileSync(BASELINE, `${JSON.stringify(current, null, 2)}\n`);
return;
}
const problems = gained(current, JSON.parse(readFileSync(BASELINE, "utf8")));
if (problems.length === 0) return;
console.error(
"Studio's routes and history engine read the disk with fs/promises, never a *Sync call:\n" +
problems.map((line) => ` ${line}`).join("\n"),
);
process.exit(1);
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main();
@@ -0,0 +1,32 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import * as fs from "node:fs";
import { countSyncCalls, gained } from "./check-studio-server-sync-fs.mjs";
test("counts synchronous fs calls a file makes, not the ones a comment names", () => {
const source = [
"const stat = existsSync(file) ? statSync(file) : null;",
"// readFileSync(file) would hold the event loop",
"const text = await readFile(file);",
"const names = readdirSync (dir);",
"const real = realpathSync.native(dir);",
"readSync(fd, buffer); writeSync(fd, buffer); fstatSync(fd);",
].join("\n");
assert.equal(countSyncCalls(source), 7);
});
test("a file may lose synchronous fs calls, never gain one, and a new file starts at none", () => {
const baseline = { "routes/preview.ts": 4 };
assert.deepEqual(gained({ "routes/preview.ts": 3 }, baseline), []);
assert.deepEqual(gained({ "routes/preview.ts": 5, "routes/new.ts": 1 }, baseline), [
"routes/preview.ts: 5 synchronous fs calls, 4 allowed",
"routes/new.ts: 1 synchronous fs calls, 0 allowed",
]);
});
// fails without the fix: the gate kept its own list of names, so a new route calling Node 22's globSync passed.
test("every synchronous call node:fs has is counted, globSync included", () => {
const names = Object.keys(fs).filter((name) => name.endsWith("Sync"));
assert.ok(names.includes("globSync"), "this Node has globSync");
for (const name of names) assert.equal(countSyncCalls(`${name}(x);`), 1, name);
});
@@ -0,0 +1,25 @@
{
"packages/studio-server/src/history/artifactCleanup.ts": 7,
"packages/studio-server/src/history/containedPath.ts": 9,
"packages/studio-server/src/history/historyId.ts": 8,
"packages/studio-server/src/history/historyLog.ts": 5,
"packages/studio-server/src/history/ownerLock.ts": 20,
"packages/studio-server/src/history/projectHistory.ts": 21,
"packages/studio-server/src/history/pruneHistories.ts": 6,
"packages/studio-server/src/history/reclaimUncopied.ts": 1,
"packages/studio-server/src/history/snapshotRuns.ts": 24,
"packages/studio-server/src/history/videoState.ts": 5,
"packages/studio-server/src/routes/files.ts": 59,
"packages/studio-server/src/routes/fonts.ts": 4,
"packages/studio-server/src/routes/freezeFrame.ts": 7,
"packages/studio-server/src/routes/globalAssets.ts": 2,
"packages/studio-server/src/routes/lint.ts": 1,
"packages/studio-server/src/routes/loudness.ts": 1,
"packages/studio-server/src/routes/media.ts": 3,
"packages/studio-server/src/routes/peaks.ts": 1,
"packages/studio-server/src/routes/preview.ts": 7,
"packages/studio-server/src/routes/recoveryDrafts.ts": 5,
"packages/studio-server/src/routes/render.ts": 12,
"packages/studio-server/src/routes/thumbnail.ts": 11,
"packages/studio-server/src/routes/waveform.ts": 1
}