Skip to content

Write HTML. Render video. Built for agents.

fix(studio-server): stream preview media byte ranges instead of reading the whole file (#3745)

Miguel Ángel8825def610fe
diff --git a/packages/studio-server/src/routes/preview.test.ts b/packages/studio-server/src/routes/preview.test.ts
index cde15caca3..44d80f82f7 100644
--- a/packages/studio-server/src/routes/preview.test.ts
+++ b/packages/studio-server/src/routes/preview.test.ts
@@ -1,7 +1,17 @@
// fallow-ignore-file code-duplication
import { afterEach, describe, expect, it, vi } from "vitest";
import { Hono } from "hono";
-import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import {
+ closeSync,
+ ftruncateSync,
+ mkdirSync,
+ mkdtempSync,
+ openSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+ writeSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { registerPreviewRoutes } from "./preview";
@@ -1204,3 +1214,39 @@ describe("hf-proxy negotiation and media codec map injection (U3)", () => {
});
});
});
+
+describe("preview asset byte ranges", () => {
+ it("streams a slice of a media file too large to read whole", async () => {
+ // A sparse 3 GiB file costs no disk. readFileSync refuses anything over
+ // 2 GiB (ERR_FS_FILE_TOO_LARGE), so a route that buffers the whole file
+ // cannot serve a single byte of it; streaming the window must.
+ const projectDir = createProjectDir();
+ const size = 3 * 1024 * 1024 * 1024;
+ const fd = openSync(join(projectDir, "clip.mp4"), "w");
+ writeSync(fd, "WXYZ", 5_000_000);
+ ftruncateSync(fd, size);
+ closeSync(fd);
+
+ const app = new Hono();
+ registerPreviewRoutes(app, createAdapter(projectDir));
+ const res = await app.request("http://localhost/projects/demo/preview/clip.mp4", {
+ headers: { Range: "bytes=5000000-5000003" },
+ });
+ expect(res.status).toBe(206);
+ expect(res.headers.get("Content-Range")).toBe(`bytes 5000000-5000003/${size}`);
+ expect(res.headers.get("Content-Length")).toBe("4");
+ expect(await res.text()).toBe("WXYZ");
+ });
+
+ it("answers 416 for a range that starts past the end of the file", async () => {
+ const projectDir = createProjectDir();
+ writeFileSync(join(projectDir, "clip.mp4"), "abc");
+ const app = new Hono();
+ registerPreviewRoutes(app, createAdapter(projectDir));
+ const res = await app.request("http://localhost/projects/demo/preview/clip.mp4", {
+ headers: { Range: "bytes=99-200" },
+ });
+ expect(res.status).toBe(416);
+ expect(res.headers.get("Content-Range")).toBe("bytes */3");
+ });
+});
diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.ts
index ef807bf1c5..7356cf2b58 100644
--- a/packages/studio-server/src/routes/preview.ts
+++ b/packages/studio-server/src/routes/preview.ts
@@ -1,5 +1,6 @@
import type { Hono } from "hono";
-import { existsSync, readFileSync, statSync } from "node:fs";
+import { createReadStream, existsSync, readFileSync, statSync } from "node:fs";
+import { Readable } from "node:stream";
import { join, resolve } from "node:path";
import { createHash } from "node:crypto";
import { injectScriptsIntoHtml, stripEmbeddedRuntimeScripts } from "@hyperframes/core/compiler";
@@ -580,34 +581,45 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): vo
servedContentType = PROXY_VARIANT_CONFIG[proxyVariant].contentType;
}
- const buffer: Buffer = isText
- ? Buffer.from(readFileSync(file, "utf-8"), "utf-8")
- : readFileSync(servedPath);
- const totalSize = buffer.length;
+ // Text is small and keeps its utf-8 round trip in memory. Binary media
+ // streams only the requested window: Chrome refills a playing <video> or
+ // <audio> with a fresh Range request every few hundred milliseconds, and a
+ // 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 totalSize = textBuffer ? textBuffer.length : statSync(servedPath).size;
+ const bodyFor = (start: number, end: number): BodyInit =>
+ textBuffer
+ ? new Uint8Array(textBuffer.subarray(start, end + 1))
+ : (Readable.toWeb(createReadStream(servedPath, { start, end })) as ReadableStream);
// Support byte-range requests so browsers can seek audio/video elements.
const rangeHeader = c.req.header("Range");
- if (rangeHeader) {
- const match = /bytes=(\d+)-(\d*)/.exec(rangeHeader);
- if (match) {
- const start = parseInt(match[1]!, 10);
- const end = match[2] ? parseInt(match[2], 10) : totalSize - 1;
- const safeEnd = Math.min(end, totalSize - 1);
- const chunkSize = safeEnd - start + 1;
- return new Response(new Uint8Array(buffer.slice(start, safeEnd + 1)), {
- status: 206,
- headers: {
- ...cacheHeaders,
- "Content-Type": servedContentType,
- "Content-Range": `bytes ${start}-${safeEnd}/${totalSize}`,
- "Accept-Ranges": "bytes",
- "Content-Length": String(chunkSize),
- },
+ const match = rangeHeader ? /bytes=(\d+)-(\d*)/.exec(rangeHeader) : null;
+ if (match) {
+ const start = parseInt(match[1]!, 10);
+ const end = match[2] ? parseInt(match[2], 10) : totalSize - 1;
+ const safeEnd = Math.min(end, totalSize - 1);
+ if (start > safeEnd) {
+ return new Response(null, {
+ status: 416,
+ headers: { ...cacheHeaders, "Content-Range": `bytes */${totalSize}` },
});
}
+ return new Response(bodyFor(start, safeEnd), {
+ status: 206,
+ headers: {
+ ...cacheHeaders,
+ "Content-Type": servedContentType,
+ "Content-Range": `bytes ${start}-${safeEnd}/${totalSize}`,
+ "Accept-Ranges": "bytes",
+ "Content-Length": String(safeEnd - start + 1),
+ },
+ });
}
- return new Response(new Uint8Array(buffer), {
+ return new Response(totalSize > 0 ? bodyFor(0, totalSize - 1) : null, {
headers: {
...cacheHeaders,
"Content-Type": servedContentType,