Open source CapCut alternative.
TypeScript
fix(site): stabilize local performance evaluations
David Le0e9ae28c0de4
diff --git a/site/next.config.ts b/site/next.config.tsindex 115e8429..dad656ec 100644--- a/site/next.config.ts+++ b/site/next.config.ts@@ -19,6 +19,9 @@ const nextConfig: NextConfig = {// published after the deploy) is rendered in the background on that first// visit and served fully static from then on.partialPrefetching: true,+ // Keep the server origin intact when the proxy rewrites a local request.+ // Normalizing 127.0.0.1 to localhost makes Next treat it as an external hop.+ skipProxyUrlNormalize: true,// Cut (the video editor) uploads large media. Two independent limits apply:// its media route reads req.formData() (a route handler), so it isn't covered// by serverActions.bodySizeLimit; and src/proxy.ts runs on /api/cut/* on everydiff --git a/site/scripts/eval-cut-perf.ts b/site/scripts/eval-cut-perf.tsindex 5f2464a4..01ef7eee 100644--- a/site/scripts/eval-cut-perf.ts+++ b/site/scripts/eval-cut-perf.ts@@ -61,6 +61,7 @@ import { createServer as createHttpsServer } from "node:https";import path from "node:path";import { promisify } from "node:util";import { CUT_MEDIA_ORIGIN } from "../src/cut/lib/hosts";+import { lockPerfRun } from "./lib/cut-eval/perfRunLock";const SITE = path.resolve(import.meta.dir, "..");const OUT = path.resolve(SITE, "..", "dist", "cut-perf");@@ -390,10 +391,12 @@ function run(cmd: string, cmdArgs: string[]): Promise<number | null> {return new Promise((resolve, reject) => {const p = spawn(cmd, cmdArgs);let err = "";- p.stderr.on("data", (d) => (err += d.toString()));+ let out = "";+ p.stderr.on("data", (d) => (err = (err + d.toString()).slice(-8000)));+ p.stdout.on("data", (d) => (out = (out + d.toString()).slice(-8000)));p.on("error", reject);p.on("close", (code) => {- if (code !== 0) reject(new Error(`${cmd} exited ${code}: ${err.slice(-800)}`));+ if (code !== 0) reject(new Error(`${cmd} exited ${code}:\n${out}\n${err}`));resolve(code);});});@@ -912,7 +915,18 @@ async function playThrough(page: Page, duration: number): Promise<void> {// Generous: a machine given a twelfth of a CPU still has to get to the end,// and the point of the wait is that it does.{ timeout: Math.max(30_000, duration * 6000), polling: 100 }- );+ ).catch(async (error) => {+ const state = await page.evaluate(() => {+ const dev = (window as unknown as {+ __cutDev: { playheadAt(): number; useEditor: { getState(): { playing: boolean; buffering: boolean } } };+ }).__cutDev;+ const s = dev.useEditor.getState();+ return { at: dev.playheadAt(), playing: s.playing, buffering: s.buffering };+ });+ console.error(`[playback-timeout] ${JSON.stringify(state)}`);+ await dumpDetail(page, 0);+ throw error;+ });await setPlaying(page, false);}@@ -2526,6 +2540,8 @@ const audioShim = (seconds: number) => `})();`;+const hmrStates = new WeakMap<Page, { frozen: boolean }>();+async function launch(): Promise<{ browser: Browser; page: Page }> {const browser = await chromium.launch({channel: "chrome",@@ -2545,6 +2561,18 @@ async function launch(): Promise<{ browser: Browser; page: Page }> {// The fixture server's certificate is its own.ignoreHTTPSErrors: true,});+ // Next's development handshake boots the page. Once the editor is ready,+ // keep the loaded code stable throughout the measurement.+ const hmr = { frozen: false };+ await context.routeWebSocket(+ (url) => url.pathname === "/_next/hmr",+ (socket) => {+ const server = socket.connectToServer();+ server.onMessage((message) => {+ if (!hmr.frozen) socket.send(message);+ });+ }+ );// The shim is what enforces the slot limit as well as the per-frame cost, so// asking for slots on a profile that pays no CPU cost has to install it too.// Without this, `--slots 2` on a profile whose `softwareMs` is 0 parses,@@ -2676,6 +2704,7 @@ async function launch(): Promise<{ browser: Browser; page: Page }> {route.continue({ url: fixtureUrl(fixtures, "link", request.url()) }));const page = await context.newPage();+ hmrStates.set(page, hmr);if (MACHINE.cpu > 1 || MACHINE.softwareMs > 0 || arg("--slots")) {if (MACHINE.cpu > 1) {const cdp = await context.newCDPSession(page);@@ -2698,6 +2727,8 @@ async function launch(): Promise<{ browser: Browser; page: Page }> {/** Load the editor and wait until it can be driven. */async function open(page: Page, projectId: string): Promise<void> {+ const hmr = hmrStates.get(page)!;+ hmr.frozen = false;await page.goto(`${BASE}/app/p/${projectId}`, { waitUntil: "domcontentloaded", timeout: 120_000 });await page.waitForFunction(() => {@@ -2710,6 +2741,7 @@ async function open(page: Page, projectId: string): Promise<void> {undefined,{ timeout: 120_000 });+ hmr.frozen = true;}/**@@ -2913,7 +2945,16 @@ async function writeReport(results: CaseResult[]): Promise<void> {}}-main().catch((e) => {+async function runExclusive(): Promise<void> {+ const lock = CHILD ? null : await lockPerfRun();+ try {+ await main();+ } finally {+ lock?.close();+ }+}++runExclusive().catch((e) => {console.error(e);process.exit(1);});diff --git a/site/scripts/lib/cut-eval/perfRunLock.test.ts b/site/scripts/lib/cut-eval/perfRunLock.test.tsnew file mode 100644index 00000000..1525950b--- /dev/null+++ b/site/scripts/lib/cut-eval/perfRunLock.test.ts@@ -0,0 +1,15 @@+import { expect, test } from "bun:test";+import { type AddressInfo } from "node:net";+import { lockPerfRun } from "./perfRunLock";++test("performance runs exclude each other and release their lock", async () => {+ const first = await lockPerfRun(0);+ const port = (first.address() as AddressInfo).port;+ try {+ await expect(lockPerfRun(port)).rejects.toThrow("Another performance run is active");+ } finally {+ await new Promise<void>((resolve) => first.close(() => resolve()));+ }+ const next = await lockPerfRun(port);+ await new Promise<void>((resolve) => next.close(() => resolve()));+});diff --git a/site/scripts/lib/cut-eval/perfRunLock.ts b/site/scripts/lib/cut-eval/perfRunLock.tsnew file mode 100644index 00000000..b7d26c7d--- /dev/null+++ b/site/scripts/lib/cut-eval/perfRunLock.ts@@ -0,0 +1,16 @@+import { createServer, type Server } from "node:net";++/** One performance run per machine. The OS releases the lock on process exit. */+export async function lockPerfRun(port = 43199): Promise<Server> {+ const server = createServer();+ await new Promise<void>((resolve, reject) => {+ server.once("error", (error: NodeJS.ErrnoException) => {+ reject(error.code === "EADDRINUSE"+ ? new Error(`Another performance run is active or local port ${port} is occupied. Wait for it to finish before running the eval.`)+ : error);+ });+ server.listen(port, "127.0.0.1", resolve);+ });+ server.unref();+ return server;+}diff --git a/site/src/proxy.test.ts b/site/src/proxy.test.tsnew file mode 100644index 00000000..ba8b5fc4--- /dev/null+++ b/site/src/proxy.test.ts@@ -0,0 +1,46 @@+import { expect, test } from "bun:test";+import { NextRequest } from "next/server";+import nextConfig from "../next.config";+import { proxy } from "./proxy";++// skipProxyUrlNormalize supplies the original URL to the proxy at runtime.+function request(url: string) {+ const req = new NextRequest(url, { headers: { host: new URL(url).host } });+ Object.defineProperty(req, "url", { value: url });+ return req;+}++test("proxy receives the original server URL", () => {+ expect(nextConfig.skipProxyUrlNormalize).toBe(true);+});++for (const host of ["127.0.0.1:3000", "localhost:3000", "[::1]:3000", "donkeycut.com"]) {+ test(`editor rewrite preserves ${host} and its query`, async () => {+ const origin = `${host === "donkeycut.com" ? "https" : "http"}://${host}`;+ const res = await proxy(request(`${origin}/app/p/example?view=timeline`));+ expect(res.status).toBe(200);+ expect(res.headers.get("location")).toBeNull();+ expect(res.headers.get("x-middleware-rewrite")).toBe(`${origin}/cut/app/p/example?view=timeline`);+ });+}++test("a direct legacy URL redirects once to the public editor route", async () => {+ const res = await proxy(request("http://127.0.0.1:3000/cut/app/p/example?view=timeline"));+ expect(res.status).toBe(308);+ expect(res.headers.get("location")).toBe("http://127.0.0.1:3000/app/p/example?view=timeline");+ const editor = await proxy(request(res.headers.get("location")!));+ expect(editor.status).toBe(200);+ expect(editor.headers.get("location")).toBeNull();+});++test("public auth routes pass through", async () => {+ const res = await proxy(request("http://127.0.0.1:3000/sign-in"));+ expect(res.headers.get("x-middleware-next")).toBe("1");+ expect(res.headers.get("x-middleware-rewrite")).toBeNull();+});++test("www canonicalizes to the product host", async () => {+ const res = await proxy(request("https://www.donkeycut.com/app/p/example"));+ expect(res.status).toBe(308);+ expect(res.headers.get("location")).toBe("https://donkeycut.com/app/p/example");+});diff --git a/site/src/proxy.ts b/site/src/proxy.tsindex 4169d348..3e03ecc6 100644--- a/site/src/proxy.ts+++ b/site/src/proxy.ts@@ -136,7 +136,7 @@ async function suHost(req: NextRequest, pathname: string): Promise<NextResponse>// until the router follows it.const home = suSectionHome(pathname);if (home) {- const url = req.nextUrl.clone();+ const url = new URL(req.url);url.pathname = home;return NextResponse.redirect(url, 307);}@@ -157,7 +157,7 @@ async function suHost(req: NextRequest, pathname: string): Promise<NextResponse>}if (!account.superUser) return NextResponse.redirect(`${SU_APP_ORIGIN}/app`);- const url = req.nextUrl.clone();+ const url = new URL(req.url);url.pathname = `${SU_ROOT}${pathname === "/" ? "" : pathname}`;const res = NextResponse.rewrite(url);res.headers.set("X-Robots-Tag", "noindex, nofollow");@@ -174,7 +174,7 @@ export function proxy(req: NextRequest) {// Aliases (www.) canonicalize to the apex.if (isDonkeycutHost(host) && host?.split(":")[0] !== "donkeycut.com") {- const url = req.nextUrl.clone();+ const url = new URL(req.url);return NextResponse.redirect(`${DONKEYCUT_CANONICAL}${pathname}${url.search}`,308,@@ -184,7 +184,7 @@ export function proxy(req: NextRequest) {// Legacy direct /cut/… links canonicalize to the rewritten address:// /cut/app/… → /app/….if (underPath(pathname, "/cut")) {- const url = req.nextUrl.clone();+ const url = new URL(req.url);url.pathname = pathname.slice("/cut".length) || "/";return NextResponse.redirect(url, 308);}@@ -192,7 +192,7 @@ export function proxy(req: NextRequest) {if (underPath(pathname, "/api")) return NextResponse.next();if (passesThrough(pathname)) return NextResponse.next();- const url = req.nextUrl.clone();+ const url = new URL(req.url);url.pathname =pathname === "/sitemap.xml"? "/cut/sitemap.xml"