Skip to content

Open source CapCut alternative.

TypeScript

feat(site): add an async job queue with superuser job APIs

David Le3726eead79a5
diff --git a/site/prisma/Jobs.prisma b/site/prisma/Jobs.prisma
new file mode 100644
index 00000000..567f1665
--- /dev/null
+++ b/site/prisma/Jobs.prisma
@@ -0,0 +1,17 @@
+// Generic deferred work the site runs off the request path. A request writes a
+// row and publishes its id to a Cloudflare Queue; the Cut worker's queue
+// consumer calls back into /api/jobs/worker one message at a time, and the
+// creator polls the row. Job kinds and their payload schemas live in code
+// (src/lib/jobs/registry.ts).
+
+model AsyncJob {
+ id String @id @default(cuid())
+ kind String
+ payload Json
+ state String @default("queued") // queued | running | done | error
+ result Json?
+ error String?
+ createdBy String
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+}
diff --git a/site/prisma/migrations/20260731051518/migration.sql b/site/prisma/migrations/20260731051518/migration.sql
new file mode 100644
index 00000000..253a636d
--- /dev/null
+++ b/site/prisma/migrations/20260731051518/migration.sql
@@ -0,0 +1,14 @@
+-- CreateTable
+CREATE TABLE "AsyncJob" (
+ "id" TEXT NOT NULL,
+ "kind" TEXT NOT NULL,
+ "payload" JSONB NOT NULL,
+ "state" TEXT NOT NULL DEFAULT 'queued',
+ "result" JSONB,
+ "error" TEXT,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "AsyncJob_pkey" PRIMARY KEY ("id")
+);
diff --git a/site/src/app/api/jobs/[jobId]/route.ts b/site/src/app/api/jobs/[jobId]/route.ts
new file mode 100644
index 00000000..29439722
--- /dev/null
+++ b/site/src/app/api/jobs/[jobId]/route.ts
@@ -0,0 +1,31 @@
+import { NextResponse } from "next/server";
+
+import {
+ isDonkeySuperUser,
+ notFoundResponse,
+ withDonkeyAuth,
+} from "@/lib/donkey-api-auth";
+import { jobStatusResponse } from "@/lib/jobs/queue";
+import { prisma } from "@/lib/prisma";
+
+export const dynamic = "force-dynamic";
+
+type RouteContext = { params: Promise<{ jobId: string }> };
+
+// Poll one background job for its outcome.
+export const GET = withDonkeyAuth(async (request, context: RouteContext) => {
+ if (!(await isDonkeySuperUser(request.donkey.userId))) {
+ return NextResponse.json(
+ {
+ error: "Forbidden",
+ message: "Only super users can run jobs.",
+ },
+ { status: 403 },
+ );
+ }
+
+ const { jobId } = await context.params;
+ const job = await prisma.asyncJob.findUnique({ where: { id: jobId } });
+ if (!job) return notFoundResponse();
+ return jobStatusResponse(job);
+});
diff --git a/site/src/app/api/jobs/route.ts b/site/src/app/api/jobs/route.ts
new file mode 100644
index 00000000..840519fd
--- /dev/null
+++ b/site/src/app/api/jobs/route.ts
@@ -0,0 +1,112 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import type { Prisma } from "@/generated/prisma/client";
+import { isDonkeySuperUser, withDonkeyAuth } from "@/lib/donkey-api-auth";
+import { enqueueJob, healJob } from "@/lib/jobs/queue";
+import { jobKinds } from "@/lib/jobs/registry";
+import { prisma } from "@/lib/prisma";
+
+export const dynamic = "force-dynamic";
+// Without a queue configured (local dev) the job runs inline before the
+// response; give it room.
+export const maxDuration = 300;
+
+// The most recent jobs, newest first, each self-healed on the way out so a
+// lost message republishes and a crashed execution reads as an error rather
+// than running forever.
+export const GET = withDonkeyAuth(async (request) => {
+ if (!(await isDonkeySuperUser(request.donkey.userId))) {
+ return NextResponse.json(
+ {
+ error: "Forbidden",
+ message: "Only super users can run jobs.",
+ },
+ { status: 403 },
+ );
+ }
+
+ const rows = await prisma.asyncJob.findMany({
+ orderBy: { createdAt: "desc" },
+ take: 10,
+ });
+ const jobs = await Promise.all(rows.map(healJob));
+ return NextResponse.json({
+ jobs: jobs.map((job) => ({
+ id: job.id,
+ kind: job.kind,
+ state: job.state,
+ payload: job.payload,
+ result: job.result ?? undefined,
+ error: job.error ?? undefined,
+ createdAt: job.createdAt.toISOString(),
+ })),
+ });
+});
+
+const jobRequestSchema = z
+ .object({
+ kind: z.string().min(1),
+ payload: z.unknown(),
+ })
+ .strict();
+
+// Start a background job. The kind names an executor in the registry, and the
+// payload must match that kind's schema. The caller polls /api/jobs/[jobId]
+// for the outcome.
+export const POST = withDonkeyAuth(async (request) => {
+ if (!(await isDonkeySuperUser(request.donkey.userId))) {
+ return NextResponse.json(
+ {
+ error: "Forbidden",
+ message: "Only super users can run jobs.",
+ },
+ { status: 403 },
+ );
+ }
+
+ const parsed = jobRequestSchema.safeParse(await request.json());
+ if (!parsed.success) {
+ return NextResponse.json(
+ {
+ error: "Invalid request",
+ issues: parsed.error.issues.map((issue) => ({
+ path: issue.path.join("."),
+ message: issue.message,
+ })),
+ },
+ { status: 400 },
+ );
+ }
+
+ const kind = jobKinds[parsed.data.kind];
+ if (!kind) {
+ return NextResponse.json(
+ {
+ error: "Invalid request",
+ message: `Unknown job kind "${parsed.data.kind}".`,
+ },
+ { status: 400 },
+ );
+ }
+ const payload = kind.payload.safeParse(parsed.data.payload);
+ if (!payload.success) {
+ return NextResponse.json(
+ {
+ error: "Invalid request",
+ issues: payload.error.issues.map((issue) => ({
+ path: issue.path.join("."),
+ message: issue.message,
+ })),
+ },
+ { status: 400 },
+ );
+ }
+
+ const { jobId } = await enqueueJob(
+ parsed.data.kind,
+ payload.data as Prisma.InputJsonValue,
+ request.donkey.userId,
+ );
+ return NextResponse.json({ jobId });
+});
diff --git a/site/src/app/api/jobs/worker/route.ts b/site/src/app/api/jobs/worker/route.ts
new file mode 100644
index 00000000..42f05820
--- /dev/null
+++ b/site/src/app/api/jobs/worker/route.ts
@@ -0,0 +1,33 @@
+import { timingSafeEqual } from "node:crypto";
+
+import { executeJob } from "@/lib/jobs/queue";
+
+// Execution callback for queued async jobs: the Cut worker's Cloudflare Queue
+// consumer POSTs one job id at a time (see src/lib/jobs/queue.ts).
+// Deliberately not wrapped in withDonkeyAuth — the caller is a machine, not a
+// session — and gated by the shared secret instead, like the copy worker's
+// callback beside it.
+export const runtime = "nodejs";
+// A user delete can move a lot of R2 objects; give the function room to finish.
+export const maxDuration = 300;
+
+/** Constant-time bearer check: a byte-by-byte `!==` would leak the secret's
+ * length and prefix through timing. */
+function authorized(header: string, secret: string): boolean {
+ const expected = Buffer.from(`Bearer ${secret}`);
+ const got = Buffer.from(header);
+ return got.length === expected.length && timingSafeEqual(got, expected);
+}
+
+export async function POST(request: Request) {
+ const secret = process.env.JOBS_EXECUTE_SECRET;
+ const authz = request.headers.get("authorization") ?? "";
+ if (!secret || !authorized(authz, secret)) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+ const body = (await request.json().catch(() => null)) as { jobId?: unknown } | null;
+ if (typeof body?.jobId !== "string" || !body.jobId) {
+ return new Response("Bad request", { status: 400 });
+ }
+ return executeJob(body.jobId);
+}
diff --git a/site/src/lib/jobs/delete-user.ts b/site/src/lib/jobs/delete-user.ts
new file mode 100644
index 00000000..9b3335df
--- /dev/null
+++ b/site/src/lib/jobs/delete-user.ts
@@ -0,0 +1,100 @@
+import Stripe from "stripe";
+import { z } from "zod";
+
+import { deleteLibraryAssetCascade } from "@/cut/server/cloud/library";
+import { deleteProjectCascade } from "@/cut/server/cloud/projects";
+import { deletePrefix, INFERENCE_PREFIX, R2NotConfiguredError } from "@/cut/server/cloud/r2";
+import { getStripe, StripeNotConfiguredError } from "@/lib/billing/stripe";
+import { getResend, isResendConfigured } from "@/lib/email/resend";
+import { defineJob, JobFailure } from "@/lib/jobs/registry";
+import { prisma } from "@/lib/prisma";
+
+// Deletes an account and everything it owns. Order matters: the Stripe
+// customer goes first (deleting it cancels any live subscription, so a crash
+// mid-job can never leave a paying customer with no account), then the Resend
+// contact, then the Cut cloud content — per-project and per-asset cascades,
+// which also clear R2 objects and HLS ladder records — then the user-keyed
+// rows that carry no foreign key, an R2 sweep of anything left under the
+// user's prefixes, and finally the user row, whose FK cascades take sessions,
+// accounts, credits, billing, onboarding, and email settings. Every step is
+// idempotent, so a queue redelivery resumes where the last attempt stopped.
+export const deleteUserJob = defineJob(
+ z.object({ email: z.string().trim().email() }),
+ async ({ email }) => {
+ const user = await prisma.user.findUnique({ where: { email } });
+ if (!user) throw new JobFailure("No user with that email.");
+ if (user.superUser) throw new JobFailure("Refusing to delete a super user.");
+
+ if (user.stripeCustomerId) {
+ try {
+ await getStripe().customers.del(user.stripeCustomerId);
+ } catch (e) {
+ const alreadyGone =
+ e instanceof Stripe.errors.StripeError && e.code === "resource_missing";
+ if (!alreadyGone && !(e instanceof StripeNotConfiguredError)) throw e;
+ }
+ }
+
+ if (isResendConfigured()) {
+ const removed = await getResend().contacts.remove({ email: user.email });
+ if (removed.error && removed.error.name !== "not_found") {
+ throw new Error(
+ `Resend contact remove failed: ${removed.error.name}: ${removed.error.message}`,
+ );
+ }
+ }
+
+ const projects = await prisma.cutProject.findMany({
+ where: { userId: user.id },
+ select: { id: true },
+ });
+ for (const project of projects) {
+ await deleteProjectCascade(user.id, project.id);
+ }
+ const assets = await prisma.cutLibraryAsset.findMany({
+ where: { userId: user.id },
+ select: { id: true },
+ });
+ for (const asset of assets) {
+ await deleteLibraryAssetCascade(user.id, asset.id);
+ }
+
+ // What the cascades don't reach: renders and copies, media rows orphaned
+ // from any project, shares of already-gone projects, templates, folders,
+ // feature flags, the storage counter, and any waitlist entry under the
+ // same address.
+ await prisma.$transaction([
+ prisma.cutRenderJob.deleteMany({ where: { userId: user.id } }),
+ prisma.cutCopyJob.deleteMany({ where: { userId: user.id } }),
+ prisma.cutChatThread.deleteMany({ where: { userId: user.id } }),
+ prisma.cutMediaObject.deleteMany({ where: { userId: user.id } }),
+ prisma.cutProjectShare.deleteMany({ where: { userId: user.id } }),
+ prisma.cutLibraryAsset.deleteMany({ where: { userId: user.id } }),
+ prisma.cutTemplate.deleteMany({ where: { userId: user.id } }),
+ prisma.cutFolder.deleteMany({ where: { userId: user.id } }),
+ prisma.cutStorageUsage.deleteMany({ where: { userId: user.id } }),
+ prisma.userFeatureFlag.deleteMany({ where: { userId: user.id } }),
+ prisma.waitlistEntry.deleteMany({ where: { email: user.email } }),
+ ]);
+
+ // Sweep whatever object the row-driven deletes missed — exports, previews,
+ // cards, and the inference scratch that lives outside the user prefix.
+ let r2Objects = 0;
+ try {
+ r2Objects += await deletePrefix(`cut/${user.id}/`);
+ r2Objects += await deletePrefix(`${INFERENCE_PREFIX}${user.id}/`);
+ } catch (e) {
+ if (!(e instanceof R2NotConfiguredError)) throw e;
+ }
+
+ await prisma.user.delete({ where: { id: user.id } });
+
+ return {
+ email: user.email,
+ userId: user.id,
+ projects: projects.length,
+ libraryAssets: assets.length,
+ r2Objects,
+ };
+ },
+);
diff --git a/site/src/lib/jobs/queue.ts b/site/src/lib/jobs/queue.ts
new file mode 100644
index 00000000..43fff9c0
--- /dev/null
+++ b/site/src/lib/jobs/queue.ts
@@ -0,0 +1,164 @@
+// The generic async-job queue: a request writes an AsyncJob row and publishes
+// its id to the Cloudflare Queue, the queue's serial consumer (the Cut
+// worker's queue handler) calls back into /api/jobs/worker one message at a
+// time, and the creator polls the row. Mirrors the share-copy queue
+// (src/cut/server/cloud/copyQueue.ts), which stays its own pipeline because it
+// ships inside the Cut engine.
+import { NextResponse } from "next/server";
+
+import type { Prisma } from "@/generated/prisma/client";
+import { JobFailure, jobKinds } from "@/lib/jobs/registry";
+import { prisma } from "@/lib/prisma";
+
+const JOBS_QUEUE_NAME = "donkey-jobs";
+// A queued job untouched this long has likely lost its message (a failed
+// publish, a dropped delivery) — the status poll re-publishes. Double delivery
+// is safe: execution claims the row atomically.
+const STALE_QUEUED_MS = 30_000;
+// A running job untouched this long is a crashed or killed execution. The
+// claim treats such a row as reclaimable so a queue retry can run it again,
+// and the status poll surfaces it as an error instead of spinning forever.
+const STALE_RUNNING_MS = 15 * 60_000;
+
+type JobRow = NonNullable<Awaited<ReturnType<typeof prisma.asyncJob.findUnique>>>;
+
+// --- Queue publish (Cloudflare Queues REST API; producers outside Workers
+// publish over HTTP). The queue id is looked up from the name once per
+// process. Missing credentials mean no queue (local dev): the request then
+// executes the job before returning.
+
+let cachedQueueId: string | null = null;
+
+async function queueId(accountId: string, token: string): Promise<string | null> {
+ if (cachedQueueId) return cachedQueueId;
+ const res = await fetch(`https://api.cloudflare.com/client/v4/accounts/${accountId}/queues`, {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+ if (!res.ok) return null;
+ const body = (await res.json()) as {
+ result?: { queue_id?: string; id?: string; queue_name?: string }[];
+ };
+ const q = body.result?.find((r) => r.queue_name === JOBS_QUEUE_NAME);
+ cachedQueueId = q?.queue_id ?? q?.id ?? null;
+ return cachedQueueId;
+}
+
+/** Publish one job id to the jobs queue; false when unconfigured or failed. */
+async function publishJob(jobId: string): Promise<boolean> {
+ const accountId = process.env.R2_ACCOUNT_ID;
+ const token = process.env.CLOUDFLARE_QUEUES_API_TOKEN;
+ if (!accountId || !token) return false;
+ try {
+ const id = await queueId(accountId, token);
+ if (!id) return false;
+ const res = await fetch(
+ `https://api.cloudflare.com/client/v4/accounts/${accountId}/queues/${id}/messages`,
+ {
+ method: "POST",
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
+ body: JSON.stringify({ body: { jobId }, content_type: "json" }),
+ },
+ );
+ return res.ok;
+ } catch {
+ return false;
+ }
+}
+
+/** Queue the job and hand back its id; without a queue (local dev) the job
+ * runs now, before responding — a serverless response must not leave
+ * fire-and-forget work behind. */
+export async function enqueueJob(
+ kind: string,
+ payload: Prisma.InputJsonValue,
+ createdBy: string,
+): Promise<{ jobId: string }> {
+ const job = await prisma.asyncJob.create({ data: { kind, payload, createdBy } });
+ const queued = await publishJob(job.id);
+ if (!queued) await executeJob(job.id);
+ return { jobId: job.id };
+}
+
+/** Self-heal one polled row: a stale queued job re-publishes its message, and
+ * a stale running job (crashed execution) becomes an error instead of spinning
+ * the poller forever. Returns the row, refreshed when it changed. */
+export async function healJob(job: JobRow): Promise<JobRow> {
+ const idleMs = Date.now() - job.updatedAt.getTime();
+ if (job.state === "queued" && idleMs > STALE_QUEUED_MS) {
+ await publishJob(job.id);
+ } else if (job.state === "running" && idleMs > STALE_RUNNING_MS) {
+ await prisma.asyncJob.updateMany({
+ where: { id: job.id, state: "running" },
+ data: { state: "error", error: "The job stalled — try again." },
+ });
+ return (await prisma.asyncJob.findUnique({ where: { id: job.id } })) ?? job;
+ }
+ return job;
+}
+
+/** Report a job's state (healed first — see healJob). */
+export async function jobStatusResponse(job: JobRow): Promise<Response> {
+ job = await healJob(job);
+ return NextResponse.json({
+ kind: job.kind,
+ state: job.state,
+ result: job.result ?? undefined,
+ error: job.error ?? undefined,
+ });
+}
+
+/** Execute one job (called by the queue consumer through /api/jobs/worker).
+ * A 200 consumes the message (including permanent failures, which land on the
+ * job row); a 500 releases the claim and lets the queue retry. */
+export async function executeJob(jobId: string): Promise<Response> {
+ // A stale running row is a killed execution, so the claim takes it too —
+ // that way the queue's redelivery actually re-runs it instead of ack'ing.
+ const claimed = await prisma.asyncJob.updateMany({
+ where: {
+ id: jobId,
+ OR: [
+ { state: "queued" },
+ { state: "running", updatedAt: { lt: new Date(Date.now() - STALE_RUNNING_MS) } },
+ ],
+ },
+ data: { state: "running" },
+ });
+ // Already running, settled, or unknown — double delivery lands here.
+ if (claimed.count === 0) return NextResponse.json({ ok: true });
+
+ const fail = async (message: string) => {
+ await prisma.asyncJob.update({
+ where: { id: jobId },
+ data: { state: "error", error: message },
+ });
+ return NextResponse.json({ ok: true });
+ };
+
+ const job = await prisma.asyncJob.findUnique({ where: { id: jobId } });
+ if (!job) return NextResponse.json({ ok: true });
+ const kind = jobKinds[job.kind];
+ if (!kind) return fail(`Unknown job kind "${job.kind}".`);
+ if (!kind.payload.safeParse(job.payload).success) {
+ return fail("The stored job payload is invalid.");
+ }
+
+ try {
+ const result = await kind.run(job.payload);
+ await prisma.asyncJob.update({
+ where: { id: jobId },
+ data: { state: "done", result },
+ });
+ return NextResponse.json({ ok: true });
+ } catch (e) {
+ if (e instanceof JobFailure) return fail(e.message);
+ // Transient failure: release the claim so the queue's retry can run the
+ // job again from where its idempotent steps left off.
+ await prisma.asyncJob
+ .updateMany({ where: { id: jobId, state: "running" }, data: { state: "queued" } })
+ .catch(() => {});
+ return NextResponse.json(
+ { error: e instanceof Error ? e.message : "Job failed." },
+ { status: 500 },
+ );
+ }
+}
diff --git a/site/src/lib/jobs/registry.ts b/site/src/lib/jobs/registry.ts
new file mode 100644
index 00000000..27676f65
--- /dev/null
+++ b/site/src/lib/jobs/registry.ts
@@ -0,0 +1,27 @@
+import type { z } from "zod";
+
+import type { Prisma } from "@/generated/prisma/client";
+import { deleteUserJob } from "@/lib/jobs/delete-user";
+
+// Thrown by an executor when the job can never succeed — the message lands on
+// the job row as its error. Anything else thrown is transient: the claim is
+// released and the queue redelivers.
+export class JobFailure extends Error {}
+
+export type JobKind = {
+ // Validates a payload at creation time and again at execution time; a stored
+ // payload that no longer parses is a permanent failure.
+ payload: z.ZodType<unknown>;
+ run: (payload: unknown) => Promise<Prisma.InputJsonValue>;
+};
+
+export function defineJob<S extends z.ZodType<unknown>>(
+ payload: S,
+ run: (payload: z.output<S>) => Promise<Prisma.InputJsonValue>,
+): JobKind {
+ return { payload, run: (raw) => run(payload.parse(raw)) };
+}
+
+export const jobKinds: Record<string, JobKind> = {
+ "delete-user": deleteUserJob,
+};