Open source CapCut alternative.
TypeScript
fix(cut): a stopped render says what it could not reach
David Le0f43039b71b0
diff --git a/site/src/cut/lib/headless/docSession.ts b/site/src/cut/lib/headless/docSession.tsindex c1cd08b0..ba23822b 100644--- a/site/src/cut/lib/headless/docSession.ts+++ b/site/src/cut/lib/headless/docSession.ts@@ -1,4 +1,5 @@import type { HeadlessSession } from "./bind";+import { fetchWithRetry } from "./http";import { syncFontAssets } from "../fontAssets";import { syncLinkedLibrary } from "../linkedLibrary";import { serializeDoc, useEditor } from "../store";@@ -24,7 +25,11 @@ export async function openCloudProject(s: HeadlessSession,projectId: string): Promise<HeadlessDocSession> {- const res = await fetch(projectPath(s, projectId), { headers: s.headers });+ const res = await fetchWithRetry(+ projectPath(s, projectId),+ { headers: s.headers },+ `read project ${projectId}`+ );if (!res.ok) throw new Error(`Could not read project ${projectId} (${res.status}).`);const version = res.headers.get("x-cut-doc-version");if (!version)@@ -37,11 +42,17 @@ export async function openCloudProject(const fileNames = (doc.assets ?? []).map((a) => a.fileName);const signed = new Map<string, string>();if (fileNames.length > 0) {- const mint = await fetch(`${s.base}/api/cut-cloud/media/presign-get`, {- method: "POST",- headers: { "Content-Type": "application/json", ...s.headers },- body: JSON.stringify({ items: fileNames.map((fileName) => ({ projectId, fileName })) }),- }).catch(() => null);+ const mint = await fetchWithRetry(+ `${s.base}/api/cut-cloud/media/presign-get`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json", ...s.headers },+ body: JSON.stringify({ items: fileNames.map((fileName) => ({ projectId, fileName })) }),+ },+ "sign the project's media URLs",+ // A mint writes nothing; asking again just re-signs the same names.+ { retry: true }+ ).catch(() => null);if (mint?.ok) {const body = (await mint.json()) as { urls?: { fileName: string; url: string }[] };for (const u of body.urls ?? []) signed.set(u.fileName, u.url);@@ -70,13 +81,14 @@ export async function pushCloudProject(const state = useEditor.getState();if (state.projectId !== session.projectId)throw new Error("The store holds a different project than this session opened.");- const res = await fetch(+ const res = await fetchWithRetry(`${projectPath(s, session.projectId)}?v=${encodeURIComponent(session.version)}`,{method: "PUT",headers: { "Content-Type": "application/json", ...s.headers },body: JSON.stringify(serializeDoc(state)),- }+ },+ `save project ${session.projectId}`);if (res.status === 409)throw new Error("The project changed under this session — another writer holds a newer version.");diff --git a/site/src/cut/lib/headless/http.test.ts b/site/src/cut/lib/headless/http.test.tsnew file mode 100644index 00000000..295dbb69--- /dev/null+++ b/site/src/cut/lib/headless/http.test.ts@@ -0,0 +1,68 @@+import { afterEach, describe, expect, test } from "bun:test";+import { fetchWithRetry } from "./http";++const realFetch = globalThis.fetch;+afterEach(() => {+ globalThis.fetch = realFetch;+});++/** Stand in for the network: answers each call from `answers` in order. */+function stubFetch(answers: (Response | Error)[]) {+ const calls: string[] = [];+ globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {+ calls.push(String((init?.method ?? "GET").toUpperCase()));+ const next = answers[Math.min(calls.length - 1, answers.length - 1)];+ if (next instanceof Error) throw next;+ return next;+ }) as typeof fetch;+ return calls;+}++describe("fetchWithRetry", () => {+ test("a read is asked again when the gateway is out", async () => {+ const calls = stubFetch([+ new Response("", { status: 502 }),+ new Response("", { status: 502 }),+ new Response("ok", { status: 200 }),+ ]);+ const res = await fetchWithRetry("https://x/y", {}, "read the project");+ expect(res.status).toBe(200);+ expect(calls.length).toBe(3);+ });++ test("a write is sent once, so a landed save is never resent", async () => {+ // The second send would answer 409 — the doc version has already moved —+ // and a saved project would be reported as a concurrent writer.+ const calls = stubFetch([new Response("", { status: 502 })]);+ const res = await fetchWithRetry("https://x/y?v=3", { method: "PUT" }, "save the project");+ expect(res.status).toBe(502);+ expect(calls).toEqual(["PUT"]);+ });++ test("a write that says it is safe to repeat is repeated", async () => {+ const calls = stubFetch([+ new Response("", { status: 503 }),+ new Response("ok", { status: 200 }),+ ]);+ const res = await fetchWithRetry(+ "https://x/presign",+ { method: "POST" },+ "sign the media URLs",+ { retry: true }+ );+ expect(res.status).toBe(200);+ expect(calls.length).toBe(2);+ });++ test("a network that never answers names the call it gave up on", async () => {+ stubFetch([new Error("fetch failed")]);+ let message = "";+ try {+ await fetchWithRetry("https://x/y", { method: "PUT" }, "save project p1");+ } catch (err) {+ message = (err as Error).message;+ }+ expect(message).toContain("Could not save project p1");+ expect(message).toContain("fetch failed");+ });+});diff --git a/site/src/cut/lib/headless/http.ts b/site/src/cut/lib/headless/http.tsnew file mode 100644index 00000000..4dbbe9bd--- /dev/null+++ b/site/src/cut/lib/headless/http.ts@@ -0,0 +1,59 @@+/**+ * Calls a headless run makes to the hosted site, made to survive the network.+ *+ * A worker container reaches the site over the open internet, and a single+ * dropped connection there is a whole render lost: `fetch` rejects with a bare+ * "fetch failed" and the job row wears that as its reason, which tells whoever+ * asked for the export nothing about what happened or whether asking again+ * would work. So the transient failures — a refused connection, a reset, a+ * gateway that is briefly out — are retried here, and what finally reaches the+ * job says which call gave up.+ */++/** Attempts, including the first. */+const ATTEMPTS = 4;+const BACKOFF_BASE_MS = 500;++/** Statuses worth asking again about: the service is up, this instance isn't. */+const RETRY_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]);++/** Methods a second attempt is safe on: asking twice reads the same thing. */+const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);++const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));++/**+ * `fetch`, retried on the failures that pass. `what` names the call in the+ * error a caller finally sees ("read the project", "sign the media URLs").+ *+ * Only a call that can be made twice is made twice. A write cannot: a gateway+ * that drops the connection after the write commits leaves the caller unable+ * to tell a lost request from a landed one, and resending a versioned PUT+ * whose first attempt landed comes back 409 — a save reported as a concurrent+ * writer. A call that writes nothing says so with `retry`.+ */+export async function fetchWithRetry(+ url: string,+ init: RequestInit,+ what: string,+ opts: { retry?: boolean } = {}+): Promise<Response> {+ const attempts =+ (opts.retry ?? SAFE_METHODS.has((init.method ?? "GET").toUpperCase())) ? ATTEMPTS : 1;+ let last: unknown;+ for (let attempt = 1; attempt <= attempts; attempt++) {+ try {+ const res = await fetch(url, init);+ if (!RETRY_STATUS.has(res.status) || attempt === attempts) return res;+ last = new Error(`${res.status}`);+ } catch (err) {+ // An abort is the caller's own decision; nothing to retry.+ if ((err as { name?: string }).name === "AbortError") throw err;+ last = err;+ if (attempt === attempts) break;+ }+ await wait(BACKOFF_BASE_MS * 2 ** (attempt - 1));+ }+ const detail = last instanceof Error ? last.message : String(last);+ throw new Error(`Could not ${what} — the service did not answer (${detail}).`);+}diff --git a/site/src/cut/worker/main.ts b/site/src/cut/worker/main.tsindex 8f38186e..1d384ed1 100644--- a/site/src/cut/worker/main.ts+++ b/site/src/cut/worker/main.ts@@ -179,7 +179,12 @@ async function runJob(job: ClaimedJob): Promise<void> {}console.log(`[cut-worker] ${job.kind} ${job.id} done`);} catch (err) {- const message = err instanceof Error ? err.message : String(err);+ const raw = err instanceof Error ? err.message : String(err);+ // A bare network rejection reads as "fetch failed" and says nothing to+ // whoever asked for the render. The row carries words instead.+ const message = /^(fetch failed|network error|terminated)$/i.test(raw.trim())+ ? "Could not reach the service — the render stopped. Try it again."+ : raw;// A canceled job's row already says so; the running-state guard also// keeps this from resurrecting a row canceled between watcher ticks.if (!entry.canceled) {@@ -190,7 +195,7 @@ async function runJob(job: ClaimedJob): Promise<void> {}).catch(() => {});}- console.error(`[cut-worker] ${job.kind} ${job.id} ${entry.canceled ? "canceled" : "failed"}: ${message}`);+ console.error(`[cut-worker] ${job.kind} ${job.id} ${entry.canceled ? "canceled" : "failed"}: ${raw}`);// A canceled turn retires this process once its cleanup settles: the// abort tears the agent loop down, and a fresh process guarantees the// next claim starts with clean per-user transport bindings even if some