Skip to content

Open source CapCut alternative.

TypeScript

feat(site): Cut render worker on Cloudflare Containers with auto-deploy

David Lef0b524ae2e82
diff --git a/.github/workflows/deploy-cut-worker.yml b/.github/workflows/deploy-cut-worker.yml
new file mode 100644
index 00000000..feb24c3a
--- /dev/null
+++ b/.github/workflows/deploy-cut-worker.yml
@@ -0,0 +1,60 @@
+name: Deploy Cut Worker
+
+# Builds the Cut render worker bundle and deploys it to Cloudflare Containers
+# (Worker shell + container image) whenever the worker or the pipeline code it
+# reuses changes. Wrangler builds the image from site/src/cut/worker/Dockerfile
+# and pushes it to Cloudflare's registry as part of the deploy.
+
+on:
+ workflow_dispatch:
+ push:
+ branches: [main]
+ paths:
+ - site/src/cut/worker/**
+ - site/src/cut/server/exportPipeline.ts
+ - site/src/cut/server/urlDownload.ts
+ - site/src/cut/server/jobs.ts
+ - site/src/cut/server/cloud/r2.ts
+ - site/prisma/**
+ - .github/workflows/deploy-cut-worker.yml
+
+permissions:
+ contents: read
+
+concurrency:
+ group: deploy-cut-worker
+ cancel-in-progress: true
+
+jobs:
+ deploy:
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: site
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ cache: npm
+ cache-dependency-path: site/package-lock.json
+
+ - uses: oven-sh/setup-bun@v2
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Generate Prisma client
+ run: npx prisma generate
+
+ - name: Bundle worker
+ run: npm run worker:build
+
+ - name: Deploy to Cloudflare
+ uses: cloudflare/wrangler-action@v3
+ with:
+ apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+ accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
+ workingDirectory: site
+ command: deploy -c src/cut/worker/wrangler.jsonc
diff --git a/site/eslint.config.mjs b/site/eslint.config.mjs
index 05e726d1..cf4ff092 100644
--- a/site/eslint.config.mjs
+++ b/site/eslint.config.mjs
@@ -12,6 +12,9 @@ const eslintConfig = defineConfig([
"out/**",
"build/**",
"next-env.d.ts",
+ // Cloudflare Worker shell for the Cut render worker: compiled by wrangler
+ // against workers types, excluded from the site's tsconfig.
+ "src/cut/worker/cf/**",
]),
]);
diff --git a/site/src/cut/worker/Dockerfile b/site/src/cut/worker/Dockerfile
new file mode 100644
index 00000000..0d2f7723
--- /dev/null
+++ b/site/src/cut/worker/Dockerfile
@@ -0,0 +1,20 @@
+# Donkey Cut cloud render worker. Build the bundle first (npm run worker:build),
+# then build this image from site/:
+# docker build -f src/cut/worker/Dockerfile -t donkey-cut-worker .
+FROM node:22-slim
+
+# ffmpeg/ffprobe for the render pipeline; python3 runs the yt-dlp zipapp.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends ffmpeg python3 ca-certificates curl \
+ && curl -fsSL https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp \
+ -o /usr/local/bin/yt-dlp \
+ && chmod +x /usr/local/bin/yt-dlp \
+ && apt-get purge -y curl \
+ && apt-get autoremove -y \
+ && rm -rf /var/lib/apt/lists/*
+
+WORKDIR /app
+COPY dist/cut-worker/main.js ./main.js
+
+ENV NODE_ENV=production
+ENTRYPOINT ["node", "main.js"]
diff --git a/site/src/cut/worker/README.md b/site/src/cut/worker/README.md
new file mode 100644
index 00000000..c0c476a0
--- /dev/null
+++ b/site/src/cut/worker/README.md
@@ -0,0 +1,74 @@
+# Cut cloud render worker
+
+A Linux container that executes Cut web mode's background jobs — `export`,
+`preview` (hover proxy), and `import_url` — by polling the `cut_render_job`
+table and running the same pipeline code the local engine uses
+(`../server/exportPipeline.ts`, `../server/urlDownload.ts`). Media moves
+through Cloudflare R2; ffmpeg/ffprobe/yt-dlp come from the container image's
+PATH.
+
+## Build
+
+```sh
+npm run worker:build # bundles to dist/cut-worker/main.js
+docker build -f src/cut/worker/Dockerfile -t donkey-cut-worker . # from site/
+```
+
+## Run
+
+```sh
+docker run -d \
+ -e DATABASE_URL=postgres://… \
+ -e R2_ACCOUNT_ID=… \
+ -e R2_ACCESS_KEY_ID=… \
+ -e R2_SECRET_ACCESS_KEY=… \
+ donkey-cut-worker
+```
+
+Required env (secrets only — everything else is code constants):
+
+- `DATABASE_URL` — the same Postgres the hosted site uses.
+- `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` — R2 credentials
+ for the `donkey-cut` bucket.
+
+One replica is enough to start: it runs up to 2 jobs concurrently (the
+engine's cap). Replicas can be added later without coordination — the atomic
+row claim keeps them from double-running a job, and SIGTERM requeues whatever
+a replica had in flight.
+
+## Deploy (Cloudflare Containers)
+
+The worker ships as a Cloudflare Container: `cf/worker.ts` is the Worker
+shell, `wrangler.jsonc` the deployment config (1 instance, 2 vCPU / 4 GiB /
+10 GB disk). The container runs on demand, not always-on: the hosted API
+POSTs the Worker's `/wake` endpoint (bearer `CUT_WAKE_SECRET`) whenever it
+queues a job and again on every poll of a still-queued job, so a lost wake
+self-heals; `main.ts` exits after ~60s of empty queue so the container stops
+billing. Cold start is a few seconds. The hosted deployment needs
+`CUT_RENDER_WAKE_URL` (the Worker's `/wake` URL) and `CUT_RENDER_WAKE_SECRET`
+in its env to send wakes — without them, queued jobs wait for a manually run
+worker.
+
+GitHub Actions deploys automatically on push to `main` when the worker or the
+shared pipeline code changes (`.github/workflows/deploy-cut-worker.yml`).
+One-time setup:
+
+1. Cloudflare Workers Paid plan (Containers requires it).
+2. A Cloudflare API token with the "Edit Cloudflare Workers" template plus
+ Containers permissions → repo secrets `CLOUDFLARE_API_TOKEN` and
+ `CLOUDFLARE_ACCOUNT_ID`.
+3. After the first deploy, set the Worker's secrets once (from `site/`):
+ `npx wrangler secret put DATABASE_URL -c src/cut/worker/wrangler.jsonc`
+ and the same for `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`,
+ `R2_SECRET_ACCESS_KEY`, and `CUT_WAKE_SECRET` (any long random string).
+ Use the Supabase connection-pooler URL for `DATABASE_URL`.
+4. On the hosted site (Vercel env): `CUT_RENDER_WAKE_URL` = the deployed
+ Worker's URL + `/wake` (e.g.
+ `https://donkey-cut-worker.<subdomain>.workers.dev/wake`) and
+ `CUT_RENDER_WAKE_SECRET` = the same random string.
+
+Manual deploy from `site/`:
+
+```sh
+npm run worker:build && npx wrangler deploy -c src/cut/worker/wrangler.jsonc
+```
diff --git a/site/src/cut/worker/cf/worker.ts b/site/src/cut/worker/cf/worker.ts
new file mode 100644
index 00000000..059be546
--- /dev/null
+++ b/site/src/cut/worker/cf/worker.ts
@@ -0,0 +1,53 @@
+// Cloudflare Workers shell for the Cut render worker container. Wrangler
+// deploys this Worker together with the container image (../Dockerfile). The
+// container wakes on demand: the hosted API POSTs /wake whenever it queues a
+// job (and while polling a still-queued one, so a lost wake self-heals); the
+// poller in ../main.ts exits once the queue drains, stopping the container.
+// This file is compiled by wrangler, not the site's tsconfig — workers
+// globals are typed loosely on purpose.
+import { Container, getContainer } from "@cloudflare/containers";
+
+type WorkerEnv = {
+ CUT_RENDER_WORKER: unknown;
+ DATABASE_URL: string;
+ R2_ACCOUNT_ID: string;
+ R2_ACCESS_KEY_ID: string;
+ R2_SECRET_ACCESS_KEY: string;
+ CUT_WAKE_SECRET: string;
+};
+
+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).
+ sleepAfter = "15m";
+
+ constructor(ctx: unknown, env: WorkerEnv) {
+ // The Container base types come from workers-types, which this file keeps
+ // out of the site program; the runtime shapes match.
+ super(ctx as never, env as never);
+ this.envVars = {
+ DATABASE_URL: env.DATABASE_URL,
+ R2_ACCOUNT_ID: env.R2_ACCOUNT_ID,
+ R2_ACCESS_KEY_ID: env.R2_ACCESS_KEY_ID,
+ R2_SECRET_ACCESS_KEY: env.R2_SECRET_ACCESS_KEY,
+ };
+ }
+}
+
+export default {
+ async fetch(request: Request, env: WorkerEnv): Promise<Response> {
+ const url = new URL(request.url);
+ if (request.method === "POST" && url.pathname === "/wake") {
+ // Starting the container bills CPU, so the wake is not public: callers
+ // present the shared secret the hosted API holds.
+ const auth = request.headers.get("authorization") ?? "";
+ 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 });
+ }
+ return new Response("donkey-cut-worker", { status: 200 });
+ },
+};
diff --git a/site/src/cut/worker/db.ts b/site/src/cut/worker/db.ts
new file mode 100644
index 00000000..0f90c7ab
--- /dev/null
+++ b/site/src/cut/worker/db.ts
@@ -0,0 +1,56 @@
+import { prisma } from "@/lib/prisma";
+
+export { prisma };
+
+/** The columns a claimed CutRenderJob row hands the job runners. */
+export interface ClaimedJob {
+ id: string;
+ userId: string;
+ projectId: string | null;
+ kind: string;
+ spec: unknown;
+ outName: string | null;
+}
+
+/**
+ * Record a finished R2 object and keep the user's storage total in step. The
+ * upsert makes re-registering the same key (a preview re-render, a retried
+ * job) charge only the size delta instead of double-counting.
+ */
+export async function registerObject(opts: {
+ userId: string;
+ projectId: string;
+ r2Key: string;
+ fileName: string;
+ mime: string;
+ bytes: number;
+ kind: string;
+}): Promise<void> {
+ const prior = await prisma.cutMediaObject.findUnique({
+ where: { r2Key: opts.r2Key },
+ select: { bytes: true, uploadState: true },
+ });
+ const priorBytes = prior?.uploadState === "complete" ? prior.bytes : BigInt(0);
+ const delta = BigInt(opts.bytes) - priorBytes;
+ await prisma.$transaction([
+ prisma.cutMediaObject.upsert({
+ where: { r2Key: opts.r2Key },
+ create: {
+ userId: opts.userId,
+ projectId: opts.projectId,
+ r2Key: opts.r2Key,
+ fileName: opts.fileName,
+ mime: opts.mime,
+ bytes: BigInt(opts.bytes),
+ kind: opts.kind,
+ uploadState: "complete",
+ },
+ update: { bytes: BigInt(opts.bytes), uploadState: "complete" },
+ }),
+ prisma.cutStorageUsage.upsert({
+ where: { userId: opts.userId },
+ create: { userId: opts.userId, bytes: delta },
+ update: { bytes: { increment: delta } },
+ }),
+ ]);
+}
diff --git a/site/src/cut/worker/exportJob.ts b/site/src/cut/worker/exportJob.ts
new file mode 100644
index 00000000..f30055e8
--- /dev/null
+++ b/site/src/cut/worker/exportJob.ts
@@ -0,0 +1,108 @@
+import { mkdir, mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { runExport, type ExportSpec, type RenderHandle } from "../server/exportPipeline";
+import { prisma, registerObject, type ClaimedJob } from "./db";
+import { downloadToFile, exportKey, mediaKey, previewKey, uploadFile } from "./r2";
+
+/** The stored spec of an export/preview CutRenderJob: the engine export spec
+ * plus the R2 keys of the browser-rendered overlay PNGs (title/caption stills
+ * and sub_blank.png). The queueing route (cloud/jobs.ts) stores exactly this
+ * and puts the already-deduped export name on the row's outName column. */
+interface ExportJobSpec {
+ spec: ExportSpec;
+ overlays?: { name: string; key: string }[];
+}
+
+/** The job's overlay-PNG R2 keys, restricted to the job owner's own overlay
+ * namespace — the queueing route already rejects foreign keys, and this keeps
+ * the worker safe against rows written any other way. */
+export function overlayKeysOf(job: ClaimedJob): string[] {
+ const overlays = (job.spec as ExportJobSpec | null)?.overlays ?? [];
+ const prefix = `cut/${job.userId}/overlays/`;
+ return overlays
+ .map((o) => o?.key)
+ .filter((k): k is string => typeof k === "string" && k.startsWith(prefix));
+}
+
+/**
+ * Run one export or preview job: stage a project-shaped work dir (media/ +
+ * overlay PNGs in the pipeline tmp dir), render through the engine's shared
+ * pipeline, and land the mp4 back in R2. Returns what the job row records.
+ */
+export async function runExportJob(
+ job: ClaimedJob,
+ handle: RenderHandle
+): Promise<{ outputKey: string; outName: string }> {
+ const body = job.spec as ExportJobSpec;
+ const spec = body.spec;
+ if (!spec || !Array.isArray(spec.clips)) throw new Error("Malformed export spec.");
+ const projectId = job.projectId ?? spec.projectId;
+ if (!projectId) throw new Error("Export job has no project.");
+ const preview = job.kind === "preview" || spec.target === "preview";
+
+ const work = await mkdtemp(path.join(os.tmpdir(), "cut-worker-"));
+ try {
+ // The pipeline reads overlay/caption PNGs from handle.tmpDir by base name
+ // and writes its encode intermediate there too — mirror the engine's
+ // uploaded-PNG staging.
+ handle.tmpDir = path.join(work, "overlays");
+ const mediaDir = path.join(work, "media");
+ await Promise.all([mkdir(handle.tmpDir, { recursive: true }), mkdir(mediaDir, { recursive: true })]);
+
+ const mediaFiles = new Set<string>();
+ for (const c of spec.clips) if (c.file) mediaFiles.add(c.file);
+ for (const o of spec.overlayVideos ?? []) if (o.file) mediaFiles.add(o.file);
+ for (const a of spec.audio ?? []) if (a.file) mediaFiles.add(a.file);
+ const overlayPrefix = `cut/${job.userId}/overlays/`;
+ for (const o of body.overlays ?? []) {
+ if (!o.key.startsWith(overlayPrefix)) throw new Error("Invalid overlay key.");
+ }
+ await Promise.all([
+ ...[...mediaFiles].map((f) =>
+ downloadToFile(mediaKey(job.userId, projectId, f), path.join(mediaDir, path.basename(f)))
+ ),
+ ...(body.overlays ?? []).map((o) =>
+ downloadToFile(o.key, path.join(handle.tmpDir, path.basename(o.name)))
+ ),
+ ]);
+
+ const outName = preview ? "preview.mp4" : job.outName?.trim() || "export.mp4";
+ handle.outPath = path.join(work, "out", outName);
+ await mkdir(path.dirname(handle.outPath), { recursive: true });
+
+ await runExport(handle, spec, (file) => path.join(mediaDir, path.basename(file)));
+
+ // The project may have been deleted (its jobs canceled) between the
+ // watcher's last tick and now; registering the output then would charge
+ // storage nothing can ever free.
+ const live = await prisma.cutRenderJob.findUnique({
+ where: { id: job.id },
+ select: { state: true },
+ });
+ if (live?.state !== "running") throw new Error("Canceled.");
+
+ const key = preview
+ ? previewKey(job.userId, projectId)
+ : exportKey(job.userId, projectId, outName);
+ const bytes = await uploadFile(key, handle.outPath, "video/mp4");
+ await registerObject({
+ userId: job.userId,
+ projectId,
+ r2Key: key,
+ fileName: outName,
+ mime: "video/mp4",
+ bytes,
+ kind: preview ? "preview" : "export",
+ });
+ if (preview) {
+ // Best-effort: a project deleted mid-render just drops its proxy.
+ await prisma.cutProject
+ .update({ where: { id: projectId }, data: { previewKey: key } })
+ .catch(() => {});
+ }
+ return { outputKey: key, outName };
+ } finally {
+ void rm(work, { recursive: true, force: true });
+ }
+}
diff --git a/site/src/cut/worker/importUrlJob.ts b/site/src/cut/worker/importUrlJob.ts
new file mode 100644
index 00000000..3b14294b
--- /dev/null
+++ b/site/src/cut/worker/importUrlJob.ts
@@ -0,0 +1,70 @@
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { download } from "../server/urlDownload";
+import { prisma, registerObject, type ClaimedJob } from "./db";
+import { mediaKey, mimeFor, uploadFile } from "./r2";
+
+/** What an import_url job records in CutRenderJob.result — the same shape the
+ * engine's synchronous import route returns to the client. */
+export interface ImportUrlResult {
+ files: { fileName: string; title: string }[];
+ text?: string;
+}
+
+/** First variant of `base` (stem, stem-1, stem-2, …) not already `taken` —
+ * the engine's on-disk dedupe scheme, run against the project's media rows. */
+function dedupeName(base: string, taken: Set<string>): string {
+ const ext = path.extname(base);
+ const stem = base.slice(0, base.length - ext.length) || "media";
+ let name = base;
+ for (let n = 1; taken.has(name); n++) name = `${stem}-${n}${ext}`;
+ return name;
+}
+
+/**
+ * Run one import_url job: fetch the URL into a temp dir with the shared
+ * yt-dlp/tweet-photo logic, then land each file in the project's R2 media
+ * prefix with a name deduped against its existing media objects.
+ */
+export async function runImportUrlJob(
+ job: ClaimedJob,
+ isCanceled: () => boolean
+): Promise<ImportUrlResult> {
+ const { url } = (job.spec ?? {}) as { url?: string };
+ if (!url || !/^https?:\/\//i.test(url.trim())) throw new Error("Enter a valid http(s) URL.");
+ const projectId = job.projectId;
+ if (!projectId) throw new Error("Import job has no project.");
+
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "cut-dl-"));
+ try {
+ const dl = await download(url.trim(), tmp);
+ if (isCanceled()) throw new Error("Import canceled.");
+
+ const rows = await prisma.cutMediaObject.findMany({
+ where: { projectId, kind: "media" },
+ select: { fileName: true },
+ });
+ const taken = new Set(rows.map((r) => r.fileName));
+ const files: ImportUrlResult["files"] = [];
+ for (const f of dl.files) {
+ const fileName = dedupeName(path.basename(f.file), taken);
+ taken.add(fileName);
+ const key = mediaKey(job.userId, projectId, fileName);
+ const bytes = await uploadFile(key, f.file, mimeFor(fileName));
+ await registerObject({
+ userId: job.userId,
+ projectId,
+ r2Key: key,
+ fileName,
+ mime: mimeFor(fileName),
+ bytes,
+ kind: "media",
+ });
+ files.push({ fileName, title: f.title });
+ }
+ return { files, ...(dl.text ? { text: dl.text } : {}) };
+ } finally {
+ void rm(tmp, { recursive: true, force: true });
+ }
+}
diff --git a/site/src/cut/worker/main.ts b/site/src/cut/worker/main.ts
new file mode 100644
index 00000000..c049c779
--- /dev/null
+++ b/site/src/cut/worker/main.ts
@@ -0,0 +1,185 @@
+import type { Prisma } from "@/generated/prisma/client";
+import type { RenderHandle } from "../server/exportPipeline";
+import { prisma, type ClaimedJob } from "./db";
+import { overlayKeysOf, runExportJob } from "./exportJob";
+import { runImportUrlJob } from "./importUrlJob";
+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.
+
+const MAX_RUNNING = 2; // mirrors the engine's concurrent-ffmpeg cap
+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,
+// the process exits so the container stops billing; the hosted API wakes it
+// again when a job is queued.
+const IDLE_EXIT_MS = 60_000;
+
+interface ActiveJob {
+ handle: RenderHandle;
+ canceled: boolean;
+}
+
+const active = new Map<string, ActiveJob>();
+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. */
+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 },
+ });
+ if (count === 1) return c;
+ }
+ return null;
+}
+
+/** Mirror one running job to its row every WATCH_MS: push the pipeline's
+ * progress out, and pull cancellation in (a canceled — or deleted — row kills
+ * the live ffmpeg; the run then settles without touching the row again). */
+function watchJob(id: string, entry: ActiveJob): ReturnType<typeof setInterval> {
+ let written = -1;
+ return setInterval(() => {
+ void (async () => {
+ try {
+ const row = await prisma.cutRenderJob.findUnique({
+ where: { id },
+ select: { state: true },
+ });
+ if (!row || row.state === "canceled") {
+ entry.canceled = true;
+ entry.handle.error = "Canceled.";
+ entry.handle.proc?.kill("SIGKILL");
+ return;
+ }
+ const progress = entry.handle.progress;
+ if (progress !== written) {
+ written = progress;
+ await prisma.cutRenderJob.updateMany({
+ where: { id, state: "running" },
+ data: { progress },
+ });
+ }
+ } catch {
+ // Transient DB hiccup: keep watching; the run itself is unaffected.
+ }
+ })();
+ }, WATCH_MS);
+}
+
+async function runJob(job: ClaimedJob): Promise<void> {
+ const handle: RenderHandle = { tmpDir: "", outPath: "", progress: 0, log: [] };
+ const entry: ActiveJob = { handle, canceled: false };
+ active.set(job.id, entry);
+ const watcher = watchJob(job.id, entry);
+ try {
+ if (job.kind === "export" || job.kind === "preview") {
+ const { outputKey, outName } = await runExportJob(job, handle);
+ await prisma.cutRenderJob.updateMany({
+ where: { id: job.id, state: "running" },
+ data: { state: "done", progress: 1, outputKey, outName },
+ });
+ } else if (job.kind === "import_url") {
+ const result = await runImportUrlJob(job, () => entry.canceled);
+ await prisma.cutRenderJob.updateMany({
+ where: { id: job.id, state: "running" },
+ data: { state: "done", progress: 1, result: result as unknown as Prisma.InputJsonValue },
+ });
+ } else {
+ throw new Error(`Unknown job kind: ${job.kind}`);
+ }
+ console.log(`[cut-worker] ${job.kind} ${job.id} done`);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ // 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) {
+ await prisma.cutRenderJob
+ .updateMany({
+ where: { id: job.id, state: "running" },
+ data: { state: "error", error: message },
+ })
+ .catch(() => {});
+ }
+ console.error(`[cut-worker] ${job.kind} ${job.id} ${entry.canceled ? "canceled" : "failed"}: ${message}`);
+ } finally {
+ clearInterval(watcher);
+ active.delete(job.id);
+ // The overlay PNGs are single-use render inputs: delete them once the job
+ // settles. A shutdown requeues the job instead, so its overlays must
+ // survive for the retry.
+ if (!stopping) await deleteObjects(overlayKeysOf(job));
+ }
+}
+
+/** On shutdown, hand claimed work back: kill the live renders and requeue
+ * their rows so the next worker picks them up instead of stranding them in
+ * "running" forever. */
+async function stop(): Promise<void> {
+ if (stopping) return;
+ stopping = true;
+ console.log("[cut-worker] stopping…");
+ for (const [id, entry] of active) {
+ entry.canceled = true; // suppress the run's own error write
+ entry.handle.proc?.kill("SIGKILL");
+ await prisma.cutRenderJob
+ .updateMany({
+ where: { id, state: "running" },
+ data: { state: "queued", claimedAt: null, progress: 0 },
+ })
+ .catch(() => {});
+ }
+ process.exit(0);
+}
+
+async function main(): Promise<void> {
+ process.on("SIGTERM", () => void stop());
+ process.on("SIGINT", () => void stop());
+ console.log(`[cut-worker] polling for jobs (max ${MAX_RUNNING} concurrent)`);
+ const inFlight = new Set<Promise<void>>();
+ let idleSince: number | null = null;
+ while (!stopping) {
+ if (inFlight.size >= MAX_RUNNING) {
+ await Promise.race(inFlight);
+ continue;
+ }
+ let job: ClaimedJob | null = null;
+ try {
+ job = await claimNext();
+ } catch (err) {
+ console.error("[cut-worker] claim failed:", err instanceof Error ? err.message : err);
+ }
+ if (!job) {
+ if (inFlight.size === 0) {
+ idleSince ??= Date.now();
+ if (Date.now() - idleSince >= IDLE_EXIT_MS) {
+ console.log("[cut-worker] queue drained; exiting");
+ process.exit(0);
+ }
+ } else {
+ idleSince = null;
+ }
+ await sleep(IDLE_POLL_MS);
+ continue;
+ }
+ idleSince = null;
+ const run = runJob(job).finally(() => inFlight.delete(run));
+ inFlight.add(run);
+ }
+}
+
+void main();
diff --git a/site/src/cut/worker/r2.ts b/site/src/cut/worker/r2.ts
new file mode 100644
index 00000000..0916547b
--- /dev/null
+++ b/site/src/cut/worker/r2.ts
@@ -0,0 +1,104 @@
+import { createReadStream } from "node:fs";
+import { mkdir, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import type { Readable } from "node:stream";
+import {
+ DeleteObjectsCommand,
+ GetObjectCommand,
+ PutObjectCommand,
+ S3Client,
+} from "@aws-sdk/client-s3";
+
+// The worker's own R2 handle: it runs outside the Next server, so it carries
+// its own client with file-streaming helpers (multi-GB renders never buffer
+// in memory). The key scheme is the hosted API's — re-exported so worker and
+// routes can never drift apart.
+
+export {
+ projectExportKey as exportKey,
+ projectMediaKey as mediaKey,
+ projectPreviewKey as previewKey,
+} from "../server/cloud/r2";
+
+const R2_BUCKET = "donkey-cut";
+
+let client: S3Client | null = null;
+function r2(): S3Client {
+ if (!client) {
+ const accountId = process.env.R2_ACCOUNT_ID;
+ const accessKeyId = process.env.R2_ACCESS_KEY_ID;
+ const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY;
+ if (!accountId || !accessKeyId || !secretAccessKey) {
+ throw new Error("R2_ACCOUNT_ID, R2_ACCESS_KEY_ID and R2_SECRET_ACCESS_KEY are required.");
+ }
+ client = new S3Client({
+ region: "auto",
+ endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
+ credentials: { accessKeyId, secretAccessKey },
+ });
+ }
+ return client;
+}
+
+/** Best-effort bulk delete; a failure leaves strays for the GC sweep. */
+export async function deleteObjects(keys: string[]): Promise<void> {
+ if (keys.length === 0) return;
+ try {
+ await r2().send(
+ new DeleteObjectsCommand({
+ Bucket: R2_BUCKET,
+ Delete: { Objects: keys.map((Key) => ({ Key })), Quiet: true },
+ })
+ );
+ } catch {
+ // GC covers what this missed.
+ }
+}
+
+/** Stream one R2 object to `dest`, creating its directory. */
+export async function downloadToFile(key: string, dest: string): Promise<void> {
+ const res = await r2().send(new GetObjectCommand({ Bucket: R2_BUCKET, Key: key }));
+ if (!res.Body) throw new Error(`Empty R2 object: ${key}`);
+ await mkdir(path.dirname(dest), { recursive: true });
+ await writeFile(dest, res.Body as Readable);
+}
+
+/** Upload a local file to `key`, returning its byte size. */
+export async function uploadFile(key: string, file: string, contentType: string): Promise<number> {
+ const info = await stat(file);
+ await r2().send(
+ new PutObjectCommand({
+ Bucket: R2_BUCKET,
+ Key: key,
+ Body: createReadStream(file),
+ ContentLength: info.size,
+ ContentType: contentType,
+ })
+ );
+ return info.size;
+}
+
+const MIME_BY_EXT: Record<string, string> = {
+ ".mp4": "video/mp4",
+ ".mov": "video/quicktime",
+ ".m4v": "video/mp4",
+ ".webm": "video/webm",
+ ".mkv": "video/x-matroska",
+ ".mp3": "audio/mpeg",
+ ".m4a": "audio/mp4",
+ ".aac": "audio/aac",
+ ".wav": "audio/wav",
+ ".ogg": "audio/ogg",
+ ".flac": "audio/flac",
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".webp": "image/webp",
+ ".gif": "image/gif",
+ ".avif": "image/avif",
+ ".bmp": "image/bmp",
+};
+
+export function mimeFor(fileName: string): string {
+ return MIME_BY_EXT[path.extname(fileName).toLowerCase()] ?? "application/octet-stream";
+}
diff --git a/site/src/cut/worker/wrangler.jsonc b/site/src/cut/worker/wrangler.jsonc
new file mode 100644
index 00000000..ee47d37a
--- /dev/null
+++ b/site/src/cut/worker/wrangler.jsonc
@@ -0,0 +1,26 @@
+// Cloudflare deployment for the Cut render worker: one Worker (cf/worker.ts)
+// owning one container instance built from ./Dockerfile. Deploy from site/:
+// npm run worker:build && npx wrangler deploy -c src/cut/worker/wrangler.jsonc
+// Secrets (DATABASE_URL, R2_*) are set once with `wrangler secret put`, never
+// checked in.
+{
+ "name": "donkey-cut-worker",
+ "main": "cf/worker.ts",
+ "compatibility_date": "2026-07-01",
+ "containers": [
+ {
+ "class_name": "CutRenderWorker",
+ "image": "./Dockerfile",
+ // 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.
+ "instance_type": { "vcpu": 2, "memory_mib": 4096, "disk_mb": 10000 }
+ }
+ ],
+ "durable_objects": {
+ "bindings": [{ "name": "CUT_RENDER_WORKER", "class_name": "CutRenderWorker" }]
+ },
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["CutRenderWorker"] }]
+}
diff --git a/site/tsconfig.json b/site/tsconfig.json
index 7e0d0d80..6a081562 100644
--- a/site/tsconfig.json
+++ b/site/tsconfig.json
@@ -30,5 +30,5 @@
".next/dev/types/**/*.ts",
"**/*.mts"
],
- "exclude": ["node_modules", "scripts"]
+ "exclude": ["node_modules", "scripts", "src/cut/worker/cf"]
}