Skip to content

Open source CapCut alternative.

TypeScript

perf(cut): a chunk settles when its own bytes land [rebuild]

David Le1cfeef19a0aa
diff --git a/site/src/cut/lib/chunkCache.test.ts b/site/src/cut/lib/chunkCache.test.ts
index e0b16862..dd9281e6 100644
--- a/site/src/cut/lib/chunkCache.test.ts
+++ b/site/src/cut/lib/chunkCache.test.ts
@@ -3,8 +3,10 @@ import {
CHUNK_SIZE,
chunkIdentity,
chunkRuns,
+ collect,
decodeResident,
encodeResident,
+ streamRun,
} from "./chunkCache";
const signed = (path: string, query = "e=123&s=abc") =>
@@ -99,3 +101,124 @@ test("chunk size divides the byte math cleanly", () => {
expect(CHUNK_SIZE).toBe(2 * 1024 * 1024);
expect(Number.isInteger(CHUNK_SIZE)).toBe(true);
});
+
+const pattern = (from: number, len: number) => {
+ const out = new Uint8Array(len);
+ for (let i = 0; i < len; i++) out[i] = (from + i) % 251;
+ return out;
+};
+
+/** A response whose body arrives in `piece`-sized writes, so a reader sees the
+ * same partial deliveries a real link gives it. */
+const streamed = (bytes: Uint8Array, piece: number): Response =>
+ new Response(
+ new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (let at = 0; at < bytes.length; at += piece)
+ controller.enqueue(bytes.subarray(at, Math.min(at + piece, bytes.length)));
+ controller.close();
+ },
+ })
+ );
+
+/** A response with no body stream at all, the shape a cache or a polyfill hands
+ * back, which both readers fall back to `arrayBuffer()` for. */
+const whole = (bytes: Uint8Array): Response =>
+ ({ body: null, arrayBuffer: async () => bytes.slice().buffer }) as unknown as Response;
+
+/** The message a rejected read left behind, or "" when it resolved. */
+const failure = async (p: Promise<unknown>): Promise<string> => {
+ try {
+ await p;
+ return "";
+ } catch (err) {
+ return String(err);
+ }
+};
+
+describe("streamRun", () => {
+ const start = 2 * CHUNK_SIZE;
+ const total = 2 * CHUNK_SIZE + 1024;
+ const body = pattern(start, total);
+
+ const run = async (res: Response, fromZero = false) => {
+ const got: [number, Uint8Array][] = [];
+ await streamRun(res, start, start + total - 1, fromZero, (i, b) => got.push([i, b]));
+ return got;
+ };
+
+ test("hands each chunk over at its own boundary", async () => {
+ const got = await run(streamed(body, 300_000));
+ expect(got.map(([i, b]) => [i, b.length])).toEqual([
+ [2, CHUNK_SIZE],
+ [3, CHUNK_SIZE],
+ [4, 1024],
+ ]);
+ expect(got[0][1]).toEqual(pattern(start, CHUNK_SIZE));
+ expect(got[2][1]).toEqual(pattern(start + 2 * CHUNK_SIZE, 1024));
+ });
+
+ test("settles a chunk before the rest of the run arrives", async () => {
+ let release!: () => void;
+ const held = new Promise<void>((r) => (release = r));
+ const res = new Response(
+ new ReadableStream<Uint8Array>({
+ async start(controller) {
+ controller.enqueue(body.subarray(0, CHUNK_SIZE));
+ await held;
+ controller.enqueue(body.subarray(CHUNK_SIZE));
+ controller.close();
+ },
+ })
+ );
+ const got: number[] = [];
+ const done = streamRun(res, start, start + total - 1, false, (i) => got.push(i));
+ while (!got.length) await new Promise((r) => setTimeout(r, 1));
+ expect(got).toEqual([2]);
+ release();
+ await done;
+ expect(got).toEqual([2, 3, 4]);
+ });
+
+ test("skips past the front when the server ignored the range", async () => {
+ const got = await run(streamed(pattern(0, start + total), 500_000), true);
+ expect(got.map(([i]) => i)).toEqual([2, 3, 4]);
+ expect(got[0][1]).toEqual(pattern(start, CHUNK_SIZE));
+ });
+
+ test("reads a bodyless response the same way", async () => {
+ const got = await run(whole(body));
+ expect(got.map(([i, b]) => [i, b.length])).toEqual([
+ [2, CHUNK_SIZE],
+ [3, CHUNK_SIZE],
+ [4, 1024],
+ ]);
+ expect(got[1][1]).toEqual(pattern(start + CHUNK_SIZE, CHUNK_SIZE));
+ });
+
+ test("throws when the body ends early", async () => {
+ expect(await failure(run(streamed(body.subarray(0, total - 10), 300_000)))).toContain(
+ "short range"
+ );
+ expect(await failure(run(whole(body.subarray(0, total - 10))))).toContain("short range");
+ });
+});
+
+describe("collect", () => {
+ test("holds only the bytes asked for", async () => {
+ const body = pattern(0, 3 * CHUNK_SIZE);
+ const out = await collect(streamed(body, 700_000), CHUNK_SIZE, 2 * CHUNK_SIZE - 1, true);
+ expect(out).toEqual(pattern(CHUNK_SIZE, CHUNK_SIZE));
+ });
+
+ test("reads a ranged body from its own start", async () => {
+ const out = await collect(streamed(pattern(1024, 4096), 1000), 1024, 1024 + 4095, false);
+ expect(out).toEqual(pattern(1024, 4096));
+ });
+
+ test("throws when the body ends early", async () => {
+ expect(await failure(collect(streamed(pattern(0, 100), 32), 0, 199, false))).toContain(
+ "short range"
+ );
+ });
+});
diff --git a/site/src/cut/lib/chunkCache.ts b/site/src/cut/lib/chunkCache.ts
index 9151a197..827a7bc9 100644
--- a/site/src/cut/lib/chunkCache.ts
+++ b/site/src/cut/lib/chunkCache.ts
@@ -402,24 +402,29 @@ async function fetchRange(
}
}
-/** Read `[start, end]` out of a response body, holding only those bytes. When
- * `fromZero`, the body starts at byte 0 whatever was asked for, so the front
- * is streamed past and the rest is dropped without ever being buffered. */
-async function collect(
+/**
+ * Walk `[start, end]` out of a response body, handing over each stretch of
+ * wanted bytes as it arrives. When `fromZero`, the body starts at byte 0
+ * whatever was asked for, so the front is streamed past and the rest is
+ * dropped without ever being buffered. The bytes handed to `onBytes` are a
+ * view on the reader's own buffer, so a caller copies them there and then.
+ * Throws when the body ends before the range is covered.
+ */
+async function walkBody(
res: Response,
start: number,
endInclusive: number,
- fromZero: boolean
-): Promise<Uint8Array> {
+ fromZero: boolean,
+ onBytes: (bytes: Uint8Array) => void
+): Promise<void> {
const want = endInclusive - start + 1;
- const out = new Uint8Array(want);
const reader = res.body?.getReader();
if (!reader) {
const all = new Uint8Array(await res.arrayBuffer());
const from = fromZero ? start : 0;
if (all.length < from + want) throw new Error("Cloud media returned a short range.");
- out.set(all.subarray(from, from + want));
- return out;
+ onBytes(all.subarray(from, from + want));
+ return;
}
let pos = fromZero ? 0 : start; // absolute position of the next byte read
let filled = 0;
@@ -432,7 +437,7 @@ async function collect(
const from = Math.max(start, chunkStart);
const to = Math.min(endInclusive + 1, pos);
if (to > from) {
- out.set(value.subarray(from - chunkStart, to - chunkStart), from - start);
+ onBytes(value.subarray(from - chunkStart, to - chunkStart));
filled += to - from;
}
}
@@ -440,9 +445,67 @@ async function collect(
await reader.cancel().catch(() => {});
}
if (filled < want) throw new Error("Cloud media returned a short range.");
+}
+
+/** Read `[start, end]` out of a response body into one buffer. */
+export async function collect(
+ res: Response,
+ start: number,
+ endInclusive: number,
+ fromZero: boolean
+): Promise<Uint8Array> {
+ const out = new Uint8Array(endInclusive - start + 1);
+ let at = 0;
+ await walkBody(res, start, endInclusive, fromZero, (bytes) => {
+ out.set(bytes, at);
+ at += bytes.length;
+ });
return out;
}
+/**
+ * Read a run's body, handing each chunk over the moment its own bytes arrive.
+ *
+ * A run is up to `MAX_RUN` chunks in one request, which is the right shape for
+ * the network — one round trip carries eight chunks. It is the wrong shape for
+ * the reader waiting on the first of them, and that reader is usually the preview.
+ * Held until the last byte of the run lands, a read of two megabytes waits for
+ * sixteen: on a link with real headroom that is seconds of waiting for bytes
+ * that arrived at the start, and the picture sits behind the sound for every
+ * one of them. Settling at each chunk's own boundary keeps the round trip and
+ * gives the reader its bytes when they exist.
+ */
+export async function streamRun(
+ res: Response,
+ start: number,
+ endInclusive: number,
+ fromZero: boolean,
+ onChunk: (index: number, bytes: Uint8Array) => void
+): Promise<void> {
+ const first = Math.floor(start / CHUNK_SIZE);
+ const total = endInclusive - start + 1;
+ // The chunk being assembled, how much of it is filled, and how much of the
+ // run has already been handed over.
+ let chunk = new Uint8Array(Math.min(CHUNK_SIZE, total));
+ let filled = 0;
+ let done = 0;
+ await walkBody(res, start, endInclusive, fromZero, (bytes) => {
+ let at = 0;
+ while (at < bytes.length) {
+ const take = Math.min(chunk.length - filled, bytes.length - at);
+ chunk.set(bytes.subarray(at, at + take), filled);
+ filled += take;
+ at += take;
+ if (filled === chunk.length) {
+ onChunk(first + done / CHUNK_SIZE, chunk);
+ done += filled;
+ filled = 0;
+ chunk = new Uint8Array(Math.min(CHUNK_SIZE, total - done));
+ }
+ }
+ });
+}
+
/** Fetch one missing run, resolving each chunk to every reader waiting on it
* and writing it to the store as it settles. */
function startRun(state: ObjState, first: number, last: number): Promise<Uint8Array>[] {
@@ -468,14 +531,14 @@ function startRun(state: ObjState, first: number, last: number): Promise<Uint8Ar
const endB = Math.min(state.size, (last + 1) * CHUNK_SIZE) - 1;
const res = await fetchRange(state.url, startB, endB, state.ac.signal);
if (!res.ok) throw new Error(`Cloud media read failed (${res.status}).`);
- const body = await collect(res, startB, endB, res.status !== 206);
- for (let i = first; i <= last; i++) {
- // A copy per chunk, so holding one chunk can't pin the whole run.
- const bytes = body.slice((i - first) * CHUNK_SIZE, (i - first + 1) * CHUNK_SIZE);
+ // Each chunk is its own array, so holding one can't pin the whole run,
+ // and it settles the moment its own bytes are here.
+ await streamRun(res, startB, endB, res.status !== 206, (i, bytes) => {
settles[i - first].resolve(bytes);
void persistChunk(state, i, bytes);
- }
+ });
} catch (err) {
+ // A chunk already handed over ignores this; the rest of the run fails.
for (const s of settles) s.reject(err);
}
})();