Open source CapCut alternative.
TypeScript
fix(site): back off when the firewall throttles [rebuild]
David Le3c9cb28c3b02
diff --git a/site/src/cut/lib/backend/cloud.ts b/site/src/cut/lib/backend/cloud.tsindex 49275259..6060163d 100644--- a/site/src/cut/lib/backend/cloud.ts+++ b/site/src/cut/lib/backend/cloud.ts@@ -3,6 +3,7 @@// the session). Routes mirror the engine's JSON shapes under /api/cut-cloud.// Media bytes ride presigned R2 URLs minted by those routes, not this// transport.+import { throttleWait } from "../network";import { observeOperationResponse, operationFailure } from "../operationFailure";import { UserError } from "../userError";import { DOC_SEQ_HEADER, DOC_WRITER_HEADER, HTTP_CONFLICT, type CutBackend, type CutRequestInit } from "./types";@@ -22,12 +23,34 @@ export function bindCloudSession(base: string, headers: Record<string, string>)* page, the bound session's origin and headers in a headless process. */type CloudSession = { base: string; headers: Record<string, string> } | null;-function requestWithSession(bound: CloudSession, path: string, init?: RequestInit): Promise<Response> {+async function requestWithSession(bound: CloudSession, path: string, init?: RequestInit): Promise<Response> {const headers = new Headers(bound?.headers);new Headers(init?.headers).forEach((value, key) => headers.set(key, value));- return fetch((bound?.base ?? "") + path, { ...init, headers }).then(observeOperationResponse);++ // The firewall refuses a burst from one address before any route runs+ // (site/firewall/), so the same request goes again once the window passes.+ // A route that throttles answers JSON with its reason, and that stands.+ for (let attempt = 1; ; attempt++) {+ const res = await fetch((bound?.base ?? "") + path, { ...init, headers });+ const wait = throttleWait(res);+ if (wait === null || attempt > FIREWALL_RETRIES || !firewallRefusal(res) || !resendable(init?.body) || init?.signal?.aborted) {+ return observeOperationResponse(res);+ }+ await res.body?.cancel().catch(() => {});+ await new Promise((r) => setTimeout(r, wait));+ }}+// How many times a request the firewall refused goes again.+const FIREWALL_RETRIES = 2;++/** Whether a throttle came from the firewall: its refusal is plain text. */+const firewallRefusal = (res: Response) => !/json/i.test(res.headers.get("content-type") ?? "");++/** Whether a request body can be sent a second time: a stream is spent once+ * read, e.g. a piped upload. */+const resendable = (body: RequestInit["body"]) => !(typeof ReadableStream !== "undefined" && body instanceof ReadableStream);+export function cloudRequest(path: string, init?: RequestInit): Promise<Response> {return requestWithSession(session, path, init);}diff --git a/site/src/cut/lib/backend/cloudCapture.test.ts b/site/src/cut/lib/backend/cloudCapture.test.tsindex 5a4dd867..4cd6e123 100644--- a/site/src/cut/lib/backend/cloudCapture.test.ts+++ b/site/src/cut/lib/backend/cloudCapture.test.ts@@ -37,3 +37,28 @@ test("each transport saves as its own writer, numbering its saves in order", asyexpect(sent.map((h) => h.get(DOC_SEQ_HEADER))).toEqual(["1", "2", "1"]);} finally { fetcher.mockRestore(); }});++test("a request the firewall throttled goes again once its window passes", async () => {+ const answers = [+ new Response("Too Many Requests", { status: 429, headers: { "Retry-After": "0", "Content-Type": "text/plain" } }),+ Response.json({ key: "k", url: "https://media.invalid/k" }),+ ];+ const fetcher = spyOn(globalThis, "fetch").mockImplementation((async () => answers.shift()!) as typeof fetch);+ try {+ const res = await cloudBackend.fetch("/api/cut/media/presign", { method: "POST", body: "{}" });+ expect(res.status).toBe(200);+ expect(fetcher.mock.calls.length).toBe(2);+ } finally { fetcher.mockRestore(); }+});++test("a throttle a route answers itself stands", async () => {+ // "Too many turns are running": the route's own verdict, with its reason.+ const fetcher = spyOn(globalThis, "fetch").mockImplementation(+ (async () => Response.json({ error: "Too many turns are running on this account." }, { status: 429 })) as typeof fetch+ );+ try {+ const res = await cloudBackend.fetch("/api/cut/turns", { method: "POST", body: "{}" });+ expect(res.status).toBe(429);+ expect(fetcher.mock.calls.length).toBe(1);+ } finally { fetcher.mockRestore(); }+});diff --git a/site/src/cut/lib/chunkCache.ts b/site/src/cut/lib/chunkCache.tsindex a2be9de9..6940199e 100644--- a/site/src/cut/lib/chunkCache.ts+++ b/site/src/cut/lib/chunkCache.ts@@ -53,6 +53,7 @@ import {} from "./backend/browser/opfs";import { CUT_MEDIA_ORIGIN } from "./hosts";import { allowance, holdMemory } from "./memoryBudget";+import { throttleWait } from "./network";import { observeOperationResponse } from "./operationFailure";export const CHUNK_SIZE = 2 * 1024 * 1024;@@ -529,6 +530,7 @@ async function fetchRange(let delay = 400;for (let attempt = 1; ; attempt++) {if (signal?.aborted) throw new DOMException("Aborted", "AbortError");+ let wait = delay;try {const res = await fetch(url, {headers: { Range: `bytes=${start}-${endInclusive}` },@@ -536,11 +538,16 @@ async function fetchRange(});// 4xx is the URL's own verdict — an expired token re-mints upstream// (mediaLinks.ts), and retrying the same string here would stall that.- if (res.ok || attempt >= FETCH_ATTEMPTS || (res.status >= 400 && res.status < 500)) return res;+ // A throttle is the exception: the same request answers once the+ // firewall's window has passed.+ const throttled = throttleWait(res);+ if (res.ok || attempt >= FETCH_ATTEMPTS || (throttled === null && res.status >= 400 && res.status < 500)) return res;+ void res.body?.cancel().catch(() => {});+ wait = throttled ?? delay;} catch (err) {if (signal?.aborted || attempt >= FETCH_ATTEMPTS) throw err;}- await sleep(delay, signal ?? new AbortController().signal);+ await sleep(wait, signal ?? new AbortController().signal);delay *= 3;}}diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex 614b36d9..3ada0e98 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -2076,6 +2076,9 @@ function knownMissing(asset: MediaAsset): boolean {// A cloud route answers this when the request carries no session.const UNAUTHORIZED = 401;+// The firewall answers this to a burst of requests from one address; the+// enrich retry reads again after the window passes.+const TOO_MANY_REQUESTS = 429;/*** Settle a failed read of an asset's file. A file that is not there marks the@@ -2091,7 +2094,8 @@ function readFailed(asset: MediaAsset, what: string, err: unknown, subject = assconsole.warn(`${what} for ${subject}`, err);return;}- if (cloudMediaStatus(err) === UNAUTHORIZED) {+ const status = cloudMediaStatus(err);+ if (status === UNAUTHORIZED || status === TOO_MANY_REQUESTS) {console.warn(`${what} for ${subject}`, err);return;}diff --git a/site/src/cut/lib/mediaMissing.test.ts b/site/src/cut/lib/mediaMissing.test.tsindex fd9cf0e3..69ce1a3a 100644--- a/site/src/cut/lib/mediaMissing.test.ts+++ b/site/src/cut/lib/mediaMissing.test.ts@@ -120,6 +120,16 @@ describe("other read failures", () => {expect(reported).toEqual([]);});+ test("a read the firewall throttled is not reported", async () => {+ // The enrich retry reads again after the window passes.+ failure = new CloudMediaError(429);+ const asset = audio();++ await ensurePeaks(asset);++ expect(reported).toEqual([]);+ });+test("an undecodable file is reported against its stage", async () => {failure = new DOMException("Decoding error.", "EncodingError");const asset = audio();diff --git a/site/src/cut/lib/network.test.ts b/site/src/cut/lib/network.test.tsindex 58fbc364..d4987ba7 100644--- a/site/src/cut/lib/network.test.ts+++ b/site/src/cut/lib/network.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from "bun:test";-import { fetchDropped } from "./network";+import { fetchDropped, throttleWait } from "./network";describe("fetchDropped", () => {test("reads each browser's wording for a dropped request", () => {@@ -14,3 +14,22 @@ describe("fetchDropped", () => {expect(fetchDropped(new Error("Cut couldn't read this media (404)."))).toBe(false);});});++describe("throttleWait", () => {+ const throttled = (headers: Record<string, string> = {}) => new Response(null, { status: 429, headers });++ test("waits as long as the answer asks, in seconds or until a date", () => {+ expect(throttleWait(throttled({ "Retry-After": "3" }))).toBe(3_000);+ const now = Date.parse("2026-10-28T10:00:00Z");+ expect(throttleWait(throttled({ "Retry-After": "Wed, 28 Oct 2026 10:00:05 GMT" }), now)).toBe(5_000);+ });++ test("waits out the firewall's window when the answer names no wait", () => {+ expect(throttleWait(throttled())).toBe(10_000);+ });++ test("answers null for anything but a throttle", () => {+ expect(throttleWait(new Response(null, { status: 403 }))).toBeNull();+ expect(throttleWait(new Response(null, { status: 206 }))).toBeNull();+ });+});diff --git a/site/src/cut/lib/network.ts b/site/src/cut/lib/network.tsindex a023e0d4..c1bc5428 100644--- a/site/src/cut/lib/network.ts+++ b/site/src/cut/lib/network.ts@@ -30,3 +30,26 @@ export function fetchDropped(err: unknown): boolean {export function connectionLost(err: unknown): boolean {return err instanceof ConnectionLostError || fetchDropped(err) || isOffline();}++// The status a server answers a client asking too often.+const TOO_MANY_REQUESTS = 429;++/** How long to hold off a throttle that names no wait: the window the site+ * firewall counts requests in (site/firewall/). */+const THROTTLE_WAIT_MS = 10_000;++/** How long `res` asks the caller to wait before asking again, or null when it+ * is no throttle. Retry-After comes as seconds or as a date, e.g. "3". */+export function throttleWait(res: Response, now = Date.now()): number | null {+ if (res.status !== TOO_MANY_REQUESTS) {+ return null;+ }++ const header = res.headers.get("retry-after");+ if (!header) {+ return THROTTLE_WAIT_MS;+ }+ const seconds = Number(header);+ const wait = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(header) - now;+ return Number.isFinite(wait) ? Math.max(0, wait) : THROTTLE_WAIT_MS;+}