Skip to content
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/cli/src/capture/captureFile.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { mkdirSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { rememberSavedFile } from "../utils/savedThisRun.js";
import { CaptureDirRefusedError } from "./captureErrors.js";
import { removeTreeBestEffort } from "@hyperframes/core/remove-tree";
import { createStagingDir } from "@hyperframes/core/atomic-file";
Expand All @@ -24,6 +25,7 @@ function publishCaptureFileSync(
const staged = join(stagingDir, basename(path));
writeCaptureFileSync(staged, data, { ...options, flag: "wx" });
renameSync(staged, path);
rememberSavedFile(path);
} finally {
removeTreeBestEffort(stagingDir);
}
Expand All @@ -42,6 +44,7 @@ export function writeCaptureFileSync(
return publishCaptureFileSync(path, data, normalized);
}
writeFileSync(path, data, { ...normalized, mode: 0o600 });
rememberSavedFile(path);
}

function hasCode(error: unknown, ...codes: string[]): boolean {
Expand Down
12 changes: 9 additions & 3 deletions packages/cli/src/commands/motionShot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { pageNavigationTimeoutMs } from "../utils/renderArgs.js";
import { gotoWhenSent } from "../capture/navigateForCapture.js";
import { resolveCompositionViewportFromHtml } from "../utils/compositionViewport.js";
import { screenshotOnBlankPage } from "../utils/blankPageShot.js";
import { rememberSavedFile } from "../utils/savedThisRun.js";
import { waitForRuntimeReady } from "../capture/captureCompositionFrame.js";
import {
assertWebGpuAdapterAvailable,
Expand Down Expand Up @@ -66,6 +67,11 @@ export function ensureShotOutputDir(outPath: string, sourcePath?: string): void
makeOutputFolder(dirname(outPath));
}

function saveShot(outPath: string, png: Uint8Array): void {
replaceFileAtomically(outPath, png);
rememberSavedFile(outPath);
}

/** Returned by the in-browser selector resolver: which animated selectors a
* `--selector SCOPE` actually resolves to (scope itself, or its descendants),
* plus diagnostic context when nothing under the scope animates. */
Expand Down Expand Up @@ -678,7 +684,7 @@ async function captureGhostOnionSkin(
)) as string;
const b64 = String(dataUrl).replace(/^data:image\/png;base64,/, "");
if (!b64) throw new Error("ghost composite returned no data");
replaceFileAtomically(outPath, Buffer.from(b64, "base64"));
saveShot(outPath, Buffer.from(b64, "base64"));
return outPath;
}

Expand Down Expand Up @@ -734,7 +740,7 @@ async function captureRenderedSvgStrip(
});
const output = await screenshotOnBlankPage(page, (blank) => blank.setContent(markup));
if (!output) throw new Error("screenshot returned no data");
replaceFileAtomically(outPath, Buffer.from(output, "base64"));
saveShot(outPath, Buffer.from(output, "base64"));
return outPath;
}

Expand Down Expand Up @@ -777,7 +783,7 @@ async function captureMarkerOnionSkin(

const buf = await page.screenshot({ type: "png" });
if (!buf) throw new Error("screenshot returned no data");
replaceFileAtomically(outPath, buf as Uint8Array);
saveShot(outPath, buf as Uint8Array);
return outPath;
}

Expand Down
160 changes: 160 additions & 0 deletions packages/cli/src/utils/savedThisRun.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import fs, { linkSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { writeCaptureFileSync } from "../capture/captureFile.js";
import { rememberSavedFile } from "./savedThisRun.js";
import { serveStaticProjectHtml, type StaticProjectServer } from "./staticProjectServer.js";

let project: string;
let server: StaticProjectServer;

beforeEach(async () => {
project = mkdtempSync(join(tmpdir(), "hf-saved-"));
mkdirSync(join(project, "out"));
writeFileSync(join(project, "asset.png"), "the project's own picture");
server = await serveStaticProjectHtml(project, "<html></html>");
});

afterEach(async () => {
vi.restoreAllMocks();
syncBuiltinESMExports();
await server.close();
rmSync(project, { recursive: true, force: true });
});

const status = async (path: string, init?: RequestInit) =>
(await fetch(new URL(path, server.url), init)).status;

it("never serves a picture this run saved into the project", async () => {
expect(await status("out/frame-00.png")).toBe(404);
writeCaptureFileSync(join(project, "out", "frame-00.png"), "frame");
expect(await status("out/frame-00.png")).toBe(404);
const headers = { "Sec-Fetch-Site": "same-origin" };
expect(await status("out/frame-00.png?hf-proxy=alpha", { headers })).toBe(404);
expect(await status("out/frame-00.png", { headers: { Range: "bytes=0-1" } })).toBe(404);
});

it("refuses the picture under any other name for the same file", async () => {
const frame = join(project, "out", "frame-00.png");
writeCaptureFileSync(frame, "frame");
linkSync(frame, join(project, "hard.png"));
expect(await status("hard.png")).toBe(404);
if (process.platform === "win32") return;
symlinkSync(join(project, "out"), join(project, "alias"));
expect(await status("alias/frame-00.png")).toBe(404);
});

it("stops serving an asset once this run saves its picture over it", async () => {
expect(await status("asset.png")).toBe(200);
writeCaptureFileSync(join(project, "asset.png"), "frame");
expect(await status("asset.png")).toBe(404);
});

it("keeps serving every file this run did not save", async () => {
writeCaptureFileSync(join(project, "out", "frame-00.png"), "frame");
writeFileSync(join(project, "out", "made-elsewhere.png"), "another program's picture");
expect(await status("asset.png")).toBe(200);
expect(await status("out/made-elsewhere.png")).toBe(200);
});

it("serves a file another program puts where this run saved one", async () => {
const frame = join(project, "out", "frame-00.png");
writeCaptureFileSync(frame, "frame");
rememberSavedFile(join(project, "missing.png"));
rmSync(frame);
writeFileSync(join(project, "missing.png"), "new");
writeFileSync(frame, "another program's picture");
expect(await status("missing.png")).toBe(200);
expect(await status("out/frame-00.png")).toBe(200);
});

it("serves the file it checked when this run saves over it during the request", async () => {
writeFileSync(join(project, "asset.jpg"), "the project's own picture");
writeCaptureFileSync(join(project, "out", "frame-00.png"), "frame");
const open = fs.createReadStream;
let refusal: unknown;
const opened = vi.spyOn(fs, "createReadStream").mockImplementation((...args) => {
try {
writeCaptureFileSync(join(project, "asset.jpg"), "this run's own frame");
} catch (error) {
refusal = error;
}
return open(...args);
});
syncBuiltinESMExports();
const response = await fetch(new URL("asset.jpg", server.url));
expect(await response.text()).toBe("the project's own picture");
expect(opened).toHaveBeenCalledTimes(1);
// Windows may refuse to replace a file while it is open; then the project's own picture stays.
if (process.platform !== "win32") expect(refusal).toBeUndefined();
expect(await status("asset.jpg")).toBe(refusal ? 200 : 404);
});

const cannotLookUp = () => {
throw Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" });
};

it("answers, without serving it, a file it cannot look up", async () => {
writeCaptureFileSync(join(project, "out", "frame-00.png"), "frame");
vi.spyOn(fs, "statSync").mockImplementation(cannotLookUp);
vi.spyOn(fs, "fstatSync").mockImplementation(cannotLookUp);
syncBuiltinESMExports();
expect(await status("asset.png")).toBe(404);
vi.restoreAllMocks();
syncBuiltinESMExports();
expect(await status("asset.png")).toBe(200);
});

it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"answers for a file it may not open",
async () => {
fs.chmodSync(join(project, "asset.png"), 0o000);
expect(await status("asset.png")).toBe(500);
expect(await status("index.html")).toBe(200);
},
);

it("refuses a picture it saved but could not look up", async () => {
vi.spyOn(fs, "statSync").mockImplementation(cannotLookUp);
syncBuiltinESMExports();
writeCaptureFileSync(join(project, "asset.png"), "frame");
vi.restoreAllMocks();
syncBuiltinESMExports();
expect(await status("asset.png")).toBe(404);
});

it("answers a folder as a missing file", async () => {
expect(await status("out")).toBe(404);
});

it("closes every handle it opened, streamed or not", async () => {
writeFileSync(join(project, "page.html"), "<p>page</p>");
writeFileSync(join(project, "empty.txt"), "");
writeFileSync(join(project, "words.txt"), "words");
writeCaptureFileSync(join(project, "frame.png"), "frame");
const open = fs.openSync;
const handles: number[] = [];
vi.spyOn(fs, "openSync").mockImplementation((...args) => {
const handle = open(...args);
handles.push(handle);
return handle;
});
const close = vi.spyOn(fs, "closeSync");
const streamed = vi.spyOn(fs, "createReadStream");
syncBuiltinESMExports();
expect(await status("words.txt", { headers: { Range: "bytes=9-" } })).toBe(416);
expect(await status("empty.txt")).toBe(200);
expect(await status("out")).toBe(404);
expect(await status("page.html", { headers: { "Sec-Fetch-Site": "cross-site" } })).toBe(200);
expect(await (await fetch(new URL("words.txt", server.url))).text()).toBe("words");
expect(await status("frame.png")).toBe(404);
expect(handles.length).toBeGreaterThanOrEqual(5);
const streams = streamed.mock.results.map((result) => result.value as fs.ReadStream);
expect(streams).toHaveLength(1);
await expect.poll(() => streams.every((stream) => stream.closed)).toBe(true);
const byStream = streamed.mock.calls.map(([, options]) => (options as { fd: number }).fd);
const closed = close.mock.calls.map(([handle]) => handle);
expect([...closed, ...byStream].sort()).toEqual([...handles].sort());
});
29 changes: 29 additions & 0 deletions packages/cli/src/utils/savedThisRun.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { fstatSync, statSync } from "node:fs";
import { resolve } from "node:path";

// By file, not by path: a link or another letter case names the same picture. Birth time tells a reused inode apart.
const saved = new Set<string>();

function identity(file: string | number): string {
const stat =
typeof file === "number" ? fstatSync(file, { bigint: true }) : statSync(file, { bigint: true });
return `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
}

export function rememberSavedFile(path: string): void {
try {
saved.add(identity(path));
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") saved.add(resolve(path));
}
}

/** A file that cannot be looked up counts as saved: it is never served unverified. */
export function savedThisRun(path: string, openFile?: number): boolean {
if (saved.size === 0) return false;
try {
return saved.has(resolve(path)) || saved.has(identity(openFile ?? path));
} catch {
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { runContrastAudit } from "../commands/validate.js";
import { createPageDriver } from "./checkBrowser.js";
import { DEFAULT_CHECK_OPTIONS, runAuditGrid } from "./checkPipeline.js";
import type { CheckOptions, MotionSpecResolution } from "./checkTypes.js";
import { savedThisRun } from "./savedThisRun.js";

function resolveExecutable(): string | undefined {
for (const name of ["HYPERFRAMES_BROWSER_PATH", "PUPPETEER_EXECUTABLE_PATH"]) {
Expand Down Expand Up @@ -275,6 +276,7 @@ describe.skipIf(!RUNS_CHROMIUM)("screenshots stay outside the composition's page
samples: 3,
});
expect(existsSync(out)).toBe(true);
expect(savedThisRun(out)).toBe(true);
expect(handed).toEqual([]);
} finally {
rmSync(project, { recursive: true, force: true });
Expand Down
62 changes: 59 additions & 3 deletions packages/cli/src/utils/staticProjectServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
serveStaticProjectHtml,
type StaticProjectServer,
} from "./staticProjectServer.js";
import { writeCaptureFileSync } from "../capture/captureFile.js";
import { injectMediaCodecMapIntoHtml } from "@hyperframes/studio-server/media-proxy-preview";
import { MAX_OPEN_MEDIA_RANGE_BYTES } from "@hyperframes/studio-server";

Expand Down Expand Up @@ -492,6 +493,60 @@ describe("serveStaticProjectHtml transparent media proxies", () => {
expect(mocks.scanProjectMediaCodecMap).not.toHaveBeenCalled();
});

it("copies only the file it checked, when another takes its name during the codec probe", async () => {
const projectDir = mk();
const clip = join(projectDir, "clip.mp4");
writeFileSync(clip, "original-hevc-bytes");
const { ino } = fs.statSync(clip, { bigint: true });
mocks.probeAssetCodec.mockImplementationOnce(async () => {
// Windows refuses to replace the file until the server has closed the handle it checked.
await Promise.resolve();
writeFileSync(join(projectDir, "other.mp4"), "other bytes");
fs.renameSync(join(projectDir, "other.mp4"), clip);
return {
codecName: "hevc",
hasAlpha: false,
browserHostile: true,
representativeMime: null,
};
});
mocks.resolveProxy.mockRejectedValue(new FakeProxyTranscodeError("changed"));
server = await serveStaticProjectHtml(projectDir, "<html></html>");

await fetch(`${server.url}clip.mp4?hf-proxy=h264`, OWN_PAGE);
expect(mocks.resolveProxy.mock.calls[0]?.[4]).toMatchObject({ checkedSource: { ino } });
});

it.each([
["a picture this run saved", (copy: string) => writeCaptureFileSync(copy, "frame")],
["a folder", (copy: string) => fs.mkdirSync(copy)],
])("answers a copy that is %s as a missing file", async (_what, put) => {
const projectDir = mk();
writeFileSync(join(projectDir, "clip.mp4"), "original-hevc-bytes");
const copy = join(projectDir, "proxy.mp4");
mocks.resolveProxy.mockImplementation(async () => {
put(copy);
return copy;
});
server = await serveStaticProjectHtml(projectDir, "<html></html>");

expect((await fetch(`${server.url}clip.mp4?hf-proxy=h264`, OWN_PAGE)).status).toBe(404);
});

it("leaves out a copy of what this run saved while the copy was made", async () => {
const projectDir = mk();
const clip = join(projectDir, "clip.mp4");
writeFileSync(clip, "original-hevc-bytes");
writeFileSync(join(projectDir, "proxy.mp4"), "transcoded-h264-bytes");
mocks.resolveProxy.mockImplementation(async () => {
writeCaptureFileSync(clip, "this run's own picture");
return join(projectDir, "proxy.mp4");
});
server = await serveStaticProjectHtml(projectDir, "<html></html>");

expect((await fetch(`${server.url}clip.mp4?hf-proxy=h264`, OWN_PAGE)).status).toBe(404);
});

it("serves the resolved proxy's bytes for ?hf-proxy=h264 on a hostile video asset", async () => {
const projectDir = mk();
writeFileSync(join(projectDir, "clip.mp4"), "original-hevc-bytes");
Expand All @@ -508,7 +563,7 @@ describe("serveStaticProjectHtml transparent media proxies", () => {
join(projectDir, "clip.mp4"),
"h264",
undefined,
{ signal: expect.any(AbortSignal) },
{ signal: expect.any(AbortSignal), checkedSource: expect.any(Object) },
);
});

Expand Down Expand Up @@ -548,7 +603,7 @@ describe("serveStaticProjectHtml transparent media proxies", () => {
join(projectDir, "clip.mp4"),
"h264",
{ width: 2048, height: 1448 },
{ signal: expect.any(AbortSignal) },
{ signal: expect.any(AbortSignal), checkedSource: expect.any(Object) },
);
});

Expand Down Expand Up @@ -579,6 +634,7 @@ describe("serveStaticProjectHtml transparent media proxies", () => {
expect(res.status).toBe(200);
expect(await res.text()).toBe("transcoded-h264-bytes");
expect(mocks.resolveProxy).toHaveBeenCalledWith(projectDir, sourcePath, "h264", undefined, {
checkedSource: expect.any(Object),
signal: expect.any(AbortSignal),
});
},
Expand Down Expand Up @@ -608,7 +664,7 @@ describe("serveStaticProjectHtml transparent media proxies", () => {
join(projectDir, "clip.mov"),
"vp8",
undefined,
{ signal: expect.any(AbortSignal) },
{ signal: expect.any(AbortSignal), checkedSource: expect.any(Object) },
);
});

Expand Down
Loading
Loading