Files
hyperframes/packages/cli/src/utils/compositionServer.ts
T
Miguel ÁngelandHuntsDesk c54f84859d fix(studio-server): long media clips no longer leave the host unanswered (#7002)
* fix(studio-server): more than six clips on one media file no longer starve check and preview of connections

Every file server answered `Range: bytes=N-` with the rest of the file. A
media element reads that until its buffer is full, then stops reading but
keeps the response open, so each <video> held one of Chrome's six HTTP/1.1
connections to the host. With seven or more <video> clips on the server's
host, every other request queued behind them and `hyperframes check`
stalled at 0% CPU. A long recording cut into trimmed segments, each its own
<video> on the same file, is enough.

An open-ended range of audio or video now gets at most 4 MiB
(OPEN_MEDIA_RANGE_BYTES), as a normal 206 with an exact Content-Range. The
element asks for the next range as it plays or seeks. Bounded and suffix
ranges, and files that aren't media, are served as before. The helper lives
in studio-server; its preview route and the CLI's static project server and
composition server use it.

Fixes #6029

Claude-Session: https://claude.ai/code/session_014aw1z3VrTNenka3LGDBBLa

* fix(studio-server): carry the range cap's reason in names and tests, not comments

The comment ratchet doesn't let a file's comment share rise: mediaRange.ts
was 48% comments against the package's 7%, and staticProjectServer.ts gained
a line. The cap is now MAX_OPEN_MEDIA_RANGE_BYTES, and the why and the
repro stay in the three tests and #6029.

Claude-Session: https://claude.ai/code/session_014aw1z3VrTNenka3LGDBBLa

* fix(producer): the render file server bounds open-ended media ranges too

parseRangeHeader takes the response's content type and caps an open-ended
`bytes=N-` on audio or video with openRangeEnd, like the CLI and Studio
servers. The producer imports it from a new `media-range` subpath of
@hyperframes/studio-server, as it does `encoder-options`, so a render
doesn't load the rest of the package.

Claude-Session: https://claude.ai/code/session_01DW4V8HZZx5JUgMffb3juVV

* test(cli): eight clips on one file no longer leave the host unanswered

A real Chromium page buffers eight long video clips of one file from the project server and then asks the same host for another file; with open-ended ranges unbounded the request stays unanswered, with the bounded piece it is answered at once.

* docs(producer): range comments name the open-ended form in lowercase

* docs(cli): the range test's comment says what holds now

---------

Co-authored-by: HuntsDesk <hunter@talloak.com>
2026-11-02 11:03:55 +00:00

208 lines
7.8 KiB
TypeScript

// Shared scaffolding for the lightweight composition servers used by `play` and
// `present`: locating the built runtime/player/slideshow bundles, serving
// composition asset files, and binding to a free port.
import { createHash } from "node:crypto";
import { createReadStream, existsSync, readFileSync, statSync } from "node:fs";
import { resolve, dirname } from "node:path";
import { Readable } from "node:stream";
import { fileURLToPath } from "node:url";
import { getMimeType, openRangeEnd } from "@hyperframes/studio-server";
import { stripSdrPngColourTags } from "@hyperframes/core/compiler/png-colour-tags";
import { injectTagsAtHeadStart } from "@hyperframes/core/compiler/html-document";
/**
* `window.__HF_MEDIA_CODEC_MAP__` injection + proxy pre-warm for HTML served
* by `play` and the static project server. Re-exported from the
* single shared implementation in
* `packages/studio-server/src/helpers/mediaProxyPreview.ts` (also used by the
* studio preview route) so injection behavior cannot drift between surfaces.
*/
export { injectMediaCodecMapIntoHtml as injectMediaCodecMap } from "@hyperframes/studio-server/media-proxy-preview";
/** Minimal surface of a listening server (satisfied by @hono/node-server's ServerType). */
interface PortBindable {
listen(port: number): unknown;
once(event: "listening" | "error", listener: (err?: NodeJS.ErrnoException) => void): unknown;
removeListener(
event: "listening" | "error",
listener: (err?: NodeJS.ErrnoException) => void,
): unknown;
}
function helperDir(): string {
// fileURLToPath (not URL.pathname) so the Windows "/D:/..." leading-slash form
// doesn't break the bundle-path resolution below.
return dirname(fileURLToPath(import.meta.url));
}
export function resolveRuntimePath(): string | null {
const d = helperDir();
const candidates = [
resolve(d, "hyperframe.runtime.iife.js"),
resolve(d, "hyperframe-runtime.js"),
resolve(d, "..", "hyperframe-runtime.js"),
// Monorepo dev: src/<dir>/ → src/ → cli/ → packages/ then into core/dist/
resolve(d, "..", "..", "..", "core", "dist", "hyperframe.runtime.iife.js"),
];
return candidates.find((p) => existsSync(p)) ?? null;
}
export function resolvePlayerPath(): string | null {
const d = helperDir();
const candidates = [
resolve(d, "..", "..", "..", "player", "dist", "hyperframes-player.global.js"),
resolve(d, "hyperframes-player.global.js"),
resolve(d, "..", "hyperframes-player.global.js"),
];
return candidates.find((p) => existsSync(p)) ?? null;
}
export function resolveSlideshowPath(): string | null {
const d = helperDir();
const candidates = [
resolve(d, "..", "..", "..", "player", "dist", "slideshow", "hyperframes-slideshow.global.js"),
resolve(d, "hyperframes-slideshow.global.js"),
resolve(d, "..", "hyperframes-slideshow.global.js"),
];
return candidates.find((p) => existsSync(p)) ?? null;
}
/**
* Inject the runtime <script> at the top of the composition's <head>, ahead of
* every author script. Compositions read `window.__hyperframes.getVariables()`
* from an inline script at init, so a runtime appended before </body> is not
* loaded yet at that point and the documented API is undefined. The compiled
* render path hoists the runtime into <head> the same way; this keeps the
* served `play` document in parity with it. Placement falls back to before
* <body>, then to the top of the document, for fragments without a <head>.
*/
export function injectRuntime(html: string): string {
return injectTagsAtHeadStart(html, `<script src="/runtime.js"></script>`);
}
export function assetContentType(filePath: string): string {
return getMimeType(filePath);
}
/** `body` with a content validator, or a 304 when the browser already holds these bytes. */
export function revalidatedResponse(
body: string,
contentType: string,
ifNoneMatch: string | undefined,
): Response {
const etag = `"${createHash("sha256").update(body).digest("base64url").slice(0, 27)}"`;
const headers = { "Content-Type": contentType, "Cache-Control": "no-cache", ETag: etag };
if (ifNoneMatch === etag) return new Response(null, { status: 304, headers });
return new Response(body, { status: 200, headers });
}
function untaggedPngBody(filePath: string, contentType: string): Buffer | null {
return contentType === "image/png" ? stripSdrPngColourTags(readFileSync(filePath)) : null;
}
/**
* Hono-native Range/206 response for a file on disk, mirroring the inline
* Range logic in `packages/studio-server/src/routes/preview.ts`'s static
* asset route. `staticProjectServer.ts`'s raw-`node:http` counterpart is
* `serveFileWithRange`; this version converts Node's bounded file stream to a
* Fetch API stream for Hono without allocating the whole media/proxy file.
*/
export function buildRangeResponse(
filePath: string,
contentType: string,
rangeHeader: string | undefined,
ifNoneMatch?: string,
): Response {
const { size, mtimeMs } = statSync(filePath);
const last = size - 1;
// Always revalidated, so an edited asset is seen; unchanged bytes cost a 304, not a refetch.
const cache = {
"Cache-Control": "no-cache",
ETag: `"${mtimeMs.toString(36)}-${size.toString(36)}"`,
};
if (ifNoneMatch === cache.ETag) return new Response(null, { status: 304, headers: cache });
const untagged = untaggedPngBody(filePath, contentType);
if (untagged) {
const headers = {
...cache,
"Content-Type": contentType,
"Content-Length": `${untagged.length}`,
};
return new Response(new Uint8Array(untagged), { status: 200, headers });
}
const match = rangeHeader ? /^bytes=(\d*)-(\d*)$/.exec(rangeHeader.trim()) : null;
const body = (start: number, end: number): ReadableStream<Uint8Array> | null =>
size === 0
? null
: (Readable.toWeb(createReadStream(filePath, { start, end })) as ReadableStream<Uint8Array>);
if (!match) {
return new Response(body(0, last), {
status: 200,
headers: {
...cache,
"Content-Type": contentType,
"Accept-Ranges": "bytes",
"Content-Length": String(size),
},
});
}
const hasStart = match[1] !== "";
const start = hasStart ? Number(match[1]) : Math.max(0, size - Number(match[2]));
const end = !hasStart
? last
: match[2] !== ""
? Math.min(Number(match[2]), last)
: openRangeEnd(start, last, contentType);
if (start > end || start > last) {
return new Response(null, {
status: 416,
headers: { "Content-Range": `bytes */${size}`, "Accept-Ranges": "bytes" },
});
}
return new Response(body(start, end), {
status: 206,
headers: {
...cache,
"Content-Type": contentType,
"Accept-Ranges": "bytes",
"Content-Range": `bytes ${start}-${end}/${size}`,
"Content-Length": String(end - start + 1),
},
});
}
/**
* Bind `server` to the first free port at or after `startPort` (scanning up to
* 10 ports). Returns the bound port. Rejects if all candidates are in use or on
* a non-EADDRINUSE error.
*/
export async function listenOnFreePort(server: PortBindable, startPort: number): Promise<number> {
for (let attempt = 0; attempt < 10; attempt++) {
const port = startPort + attempt;
try {
await new Promise<void>((res, rej) => {
const onErr = (err?: NodeJS.ErrnoException) => {
server.removeListener("listening", onOk);
rej(err ?? new Error("server error"));
};
const onOk = () => {
server.removeListener("error", onErr);
res();
};
server.once("error", onErr);
server.once("listening", onOk);
server.listen(port);
});
return port;
} catch (err: unknown) {
if ((err as NodeJS.ErrnoException).code === "EADDRINUSE") continue;
throw err;
}
}
throw new Error(`No free port found in [${startPort}, ${startPort + 9}]`);
}