Open source CapCut alternative.
TypeScript
perf(cut): run one cloud render per container, watched work first
David Le8bef81760b6b
diff --git a/site/src/cut/worker/cf/worker.ts b/site/src/cut/worker/cf/worker.tsindex 163ecc9e..d061c647 100644--- a/site/src/cut/worker/cf/worker.ts+++ b/site/src/cut/worker/cf/worker.ts@@ -29,6 +29,15 @@ type QueueMessage = {};type QueueBatch = { messages: QueueMessage[] };+// How many container replicas the render pool runs. Each one takes a single+// job at a time, so this is also the number of renders that can be in flight+// at once. Keep it in step with max_instances in ../wrangler.jsonc; a replica+// with nothing to claim drains out on its own (IDLE_EXIT_MS in ../main.ts),+// so waking the whole pool costs idle poll time and nothing else.+const REPLICAS = 4;++const replicaName = (i: number) => `cut-render-${i}`;+export class CutRenderWorker extends Container<WorkerEnv> {// Backstop only: main.ts exits by itself when the queue drains. This stops// a hung process that no longer polls (and so can't exit).@@ -68,9 +77,24 @@ export default {if (!env.CUT_WAKE_SECRET || auth !== `Bearer ${env.CUT_WAKE_SECRET}`) {return new Response("Unauthorized", { status: 401 });}- // start() is a no-op while the container runs and a boot after a sleep.- await getContainer(env.CUT_RENDER_WORKER as never).start();- return Response.json({ ok: true });+ // Wake the whole pool: the queue is drained by whichever replicas are up,+ // and each claim is atomic, so starting them all is how a burst of jobs+ // renders in parallel instead of one at a time. start() is a no-op on a+ // replica already running and a boot on one that slept.+ const starts = await Promise.allSettled(+ Array.from({ length: REPLICAS }, (_, i) =>+ getContainer(env.CUT_RENDER_WORKER as never, replicaName(i)).start()+ )+ );+ const started = starts.filter((s) => s.status === "fulfilled").length;+ // Some replicas failing still drains the queue, just slower. All of them+ // failing means no render can ever run, which has to be loud.+ if (started === 0) {+ const first = starts.find((s) => s.status === "rejected");+ const why = first?.status === "rejected" ? String(first.reason) : "unknown";+ return new Response(`No render replica started: ${why}`, { status: 500 });+ }+ return Response.json({ ok: true, started });}return new Response("donkey-cut-worker", { status: 200 });},diff --git a/site/src/cut/worker/main.ts b/site/src/cut/worker/main.tsindex 01c0f3ec..b65cb21f 100644--- a/site/src/cut/worker/main.ts+++ b/site/src/cut/worker/main.ts@@ -8,10 +8,14 @@ import { deleteObjects } from "./r2";// The cloud render worker: a headless loop that claims CutRenderJob rows the// hosted API queues (export, preview, import_url), executes them with the// same pipeline code the local engine runs, and writes progress and results-// back to the row the client polls. One process, MAX_RUNNING jobs at a time,-// horizontal scale by adding replicas — the atomic claim keeps them apart.+// back to the row the client polls. Scale is horizontal: one job per process,+// several processes — the atomic claim keeps them apart.-const MAX_RUNNING = 2; // mirrors the engine's concurrent-ffmpeg cap+// One render per replica: ffmpeg already threads across every core it is given,+// so a second concurrent job halves the first one's cores and doubles how long+// someone watches a progress bar. Parallelism comes from replicas instead+// (max_instances / REPLICAS, wrangler.jsonc + cf/worker.ts).+const MAX_RUNNING = 1;const IDLE_POLL_MS = 2000;const WATCH_MS = 1000; // progress write + cancellation check cadence// Drain-and-exit: once the queue stays empty this long with nothing running,@@ -41,21 +45,33 @@ let stopping = false;const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));-/** Atomically claim the oldest queued job: the updateMany's state guard makes- * exactly one worker win each row, so replicas never double-run a job. */+/** The kinds someone is watching happen: an export or a URL import has a+ * progress bar on screen, while a hover proxy and a share card are background+ * polish nobody is waiting on. */+const WATCHED_KINDS = ["export", "import_url"];++/** Atomically claim the next queued job: the updateMany's state guard makes+ * exactly one worker win each row, so replicas never double-run a job.+ *+ * Watched kinds go first, FIFO within a tier. Strict FIFO across all kinds let+ * a proxy render queued moments earlier hold up an export the user is staring+ * at — the wait was invisible in the UI, because the export's elapsed clock+ * only starts once it is claimed. */async function claimNext(): Promise<ClaimedJob | null> {- const candidates = await prisma.cutRenderJob.findMany({- where: { state: "queued" },- orderBy: { createdAt: "asc" },- take: 5,- select: { id: true, userId: true, projectId: true, kind: true, spec: true, outName: true },- });- for (const c of candidates) {- const { count } = await prisma.cutRenderJob.updateMany({- where: { id: c.id, state: "queued" },- data: { state: "running", claimedAt: new Date(), progress: 0, error: null },+ for (const kind of [{ in: WATCHED_KINDS }, { notIn: WATCHED_KINDS }]) {+ const candidates = await prisma.cutRenderJob.findMany({+ where: { state: "queued", kind },+ orderBy: { createdAt: "asc" },+ take: 5,+ select: { id: true, userId: true, projectId: true, kind: true, spec: true, outName: true },});- if (count === 1) return c;+ for (const c of candidates) {+ const { count } = await prisma.cutRenderJob.updateMany({+ where: { id: c.id, state: "queued" },+ data: { state: "running", claimedAt: new Date(), progress: 0, error: null },+ });+ if (count === 1) return c;+ }}return null;}diff --git a/site/src/cut/worker/wrangler.jsonc b/site/src/cut/worker/wrangler.jsoncindex 5ecfb11f..f8322de0 100644--- a/site/src/cut/worker/wrangler.jsonc+++ b/site/src/cut/worker/wrangler.jsonc@@ -16,10 +16,17 @@// The Dockerfile copies dist/cut-worker/main.js, so the build context is// the site root (three levels up from this file)."image_build_context": "../../..",- "max_instances": 1,- // ffmpeg encodes are CPU-bound; exports also stage media on disk.- // Cloudflare validation: >= 3 GiB memory per vCPU, disk <= 2x memory.- "instance_type": { "vcpu": 2, "memory_mib": 6144, "disk_mb": 10000 }+ // Renders scale out, not up: each replica runs ONE job on the whole box+ // (MAX_RUNNING in ../main.ts), so an export never splits cores with+ // another render or queues behind someone else's. Keep this in step with+ // REPLICAS in cf/worker.ts — that constant is what /wake starts.+ "max_instances": 4,+ // The platform maximum (4 vCPU / 12 GiB / 20 GB). ffmpeg encodes are+ // CPU-bound and x264 scales nearly linearly across threads, and container+ // CPU bills on active use rather than provisioned, so the wider box costs+ // about the same per render and finishes in half the time. Cloudflare+ // validation: >= 3 GiB memory per vCPU, disk <= 2x memory.+ "instance_type": { "vcpu": 4, "memory_mib": 12288, "disk_mb": 20000 }}],"durable_objects": {