Open source CapCut alternative.
TypeScript
feat(site): queue project copies through Cloudflare Queues
David Le09f5347c4421
diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prismaindex 0916ce0c..d1d9f0d7 100644--- a/site/prisma/Cut.prisma+++ b/site/prisma/Cut.prisma@@ -36,6 +36,26 @@ model CutProjectShare {@@index([userId])}+// One requested project copy — a share copy into a viewer's account, or an+// owner duplicating their own project. Copies move whole projects' worth of+// R2 objects, so they never run in the request that asked: the request writes+// this row and publishes its id to a Cloudflare Queue, the queue's serial+// consumer executes it, and the client polls this row for the outcome.+model CutCopyJob {+ id String @id @default(cuid())+ kind String @default("share") // share | duplicate+ shareId String? // share: access re-checked against this row at drain time+ projectId String? // duplicate: the owner's source project+ userId String // destination account (the viewer, or the owner)+ state String @default("queued") // queued | running | done | error+ newProjectId String?+ error String?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([userId, createdAt])+}+model CutFolder {id String @id @default(cuid())userId Stringdiff --git a/site/src/app/api/cut-copy-worker/route.ts b/site/src/app/api/cut-copy-worker/route.tsnew file mode 100644index 00000000..71b25778--- /dev/null+++ b/site/src/app/api/cut-copy-worker/route.ts@@ -0,0 +1,32 @@+import { timingSafeEqual } from "node:crypto";+import { executeCopyJob } from "@/cut/server/cloud/copyQueue";++// Execution callback for queued share-copies: the Cut worker's Cloudflare+// Queue consumer POSTs one job id at a time (see cut/server/cloud/copyQueue.ts).+// Deliberately not wrapped in withDonkeyAuth — the caller is a machine, not a+// session — and gated by the shared secret instead, like the render worker's+// wake in the other direction.+export const runtime = "nodejs";+// A big project copies many 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.CUT_COPY_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 executeCopyJob(body.jobId);+}diff --git a/site/src/app/api/cut-shared/[[...slug]]/route.ts b/site/src/app/api/cut-shared/[[...slug]]/route.tsnew file mode 100644index 00000000..61a5ba57--- /dev/null+++ b/site/src/app/api/cut-shared/[[...slug]]/route.ts@@ -0,0 +1,15 @@+import { cutSharedCatchAll } from "@/cut/server/cloud/sharedRoutes";++// The shared-viewer API: read-only access to a shared cloud project by link+// token. Deliberately NOT wrapped in withDonkeyAuth — a public share must open+// with no session — so this is one of the named public exceptions (see+// docs/guides/backend-apis.md). Access control happens per request inside the+// route table's share resolver, and content is filtered to the share's+// settings before it leaves the server.+export const runtime = "nodejs";++const handle = (request: Request) => cutSharedCatchAll(request);++export const GET = handle;+export const POST = handle;+export const HEAD = handle;diff --git a/site/src/cut/server/cloud/copyQueue.ts b/site/src/cut/server/cloud/copyQueue.tsnew file mode 100644index 00000000..c7cf5501--- /dev/null+++ b/site/src/cut/server/cloud/copyQueue.ts@@ -0,0 +1,387 @@+// Project-copy jobs: a viewer copying a share into their own account, and an+// owner duplicating their own project from the dashboard. A copy moves a+// whole project's worth of R2 objects, so it never runs in the request that+// asked for it: the request writes a CutCopyJob row and publishes its id to+// the Cloudflare Queue, the queue's serial consumer (the Cut worker's queue+// handler) calls back into /api/cut-copy-worker one message at a time, and+// the client polls the row. The serial consumer is the throttle — a burst of+// copy requests drains one copy at a time instead of stampeding R2 and the+// database all at once.+import { randomUUID } from "node:crypto";+import type { ProjectDoc } from "@/cut/lib/types";+import type { Prisma } from "@/generated/prisma/client";+import { auth } from "@/lib/auth";+import { prisma } from "@/lib/prisma";+import { copy, projectMediaKey } from "./r2";+import { normalizeEmails, normalizeFeatures } from "./share";+import { filterDocForShare, resolveShare, type ShareRow } from "./sharedView";+import { addUsage, quotaCheck } from "./usage";+import { caught, err } from "./util";++const COPY_QUEUE_NAME = "donkey-cut-copy";+// A queued job untouched this long has likely lost its message (a failed+// publish, a dropped delivery) — the status poll re-publishes, mirroring the+// render worker's self-healing wake. Double delivery is safe: execution+// claims the row atomically.+const STALE_QUEUED_MS = 30_000;+// A running job untouched this long is a crashed execution; surface the+// failure instead of spinning the viewer forever.+const STALE_RUNNING_MS = 10 * 60_000;++const QUOTA_MESSAGE =+ "Your cloud storage is full — free some space, then copy again.";++// --- 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, which is the old inline behavior.++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 === COPY_QUEUE_NAME);+ cachedQueueId = q?.queue_id ?? q?.id ?? null;+ return cachedQueueId;+}++/** Publish one job id to the copy queue; false when unconfigured or failed. */+async function publishCopyJob(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;+ }+}++// --- What a copy would move. Shared by each request's fast quota check and+// the job's execution, which re-derives it at drain time.++type MediaRow = Awaited<ReturnType<typeof prisma.cutMediaObject.findMany>>[number];++/** Everything one copy materializes: the doc to store (already filtered for+ * shares, verbatim for duplicates), where it lands, and what it carries. */+interface CopySource {+ doc: ProjectDoc;+ name: string;+ folderId: string | null;+ media: MediaRow[];+ chats: { id: string; data: unknown }[];+ added: number;+}++function completeMedia(+ ownerId: string,+ projectId: string,+ fileNames?: string[]+): Promise<MediaRow[]> {+ return prisma.cutMediaObject.findMany({+ where: {+ userId: ownerId,+ projectId,+ kind: "media",+ uploadState: "complete",+ ...(fileNames ? { fileName: { in: fileNames } } : {}),+ },+ });+}++const mediaBytes = (media: MediaRow[]) => media.reduce((sum, m) => sum + Number(m.bytes), 0);++async function copyPlan(share: ShareRow) {+ const features = normalizeFeatures(share.features);+ const row = await prisma.cutProject.findFirst({+ where: { id: share.projectId, userId: share.userId },+ });+ if (!row) return null;+ const doc = filterDocForShare(row.doc as unknown as ProjectDoc, features);+ const media = await completeMedia(share.userId, share.projectId, doc.assets.map((a) => a.fileName));+ return { features, doc, media, added: mediaBytes(media) };+}++/** A share copy's source: access re-checked at drain time, doc filtered to+ * the shared surfaces, mid-flight brief-to-video runs dropped (the copy is+ * the viewer's project — a live plan would auto-resume on their account),+ * chats only when chat is shared. Returns the permanent-failure message when+ * the copy can no longer happen. */+async function shareSource(job: { shareId: string | null; userId: string }): Promise<CopySource | string> {+ const share = job.shareId+ ? await prisma.cutProjectShare.findUnique({ where: { id: job.shareId } })+ : null;+ if (!share) return "The share was removed.";+ if (!(await viewerAllowed(share, job.userId))) {+ return "You no longer have access to this project.";+ }+ const plan = await copyPlan(share);+ if (!plan) return "The project was deleted.";+ const chats = plan.features.chat+ ? await prisma.cutChatThread.findMany({+ where: { userId: share.userId, projectId: share.projectId },+ select: { id: true, data: true },+ })+ : [];+ const gv = plan.doc.genvideo;+ return {+ doc: {+ ...plan.doc,+ genvideo: gv && (gv.phase === "done" || gv.phase === "failed") ? gv : undefined,+ },+ name: plan.doc.name,+ folderId: null,+ media: plan.media,+ chats,+ added: plan.added,+ };+}++/** An owner duplicate's source: the whole doc verbatim, same folder, media+ * only — the same shape the old synchronous duplicate produced. */+async function duplicateSource(job: {+ projectId: string | null;+ userId: string;+}): Promise<CopySource | string> {+ const row = job.projectId+ ? await prisma.cutProject.findFirst({ where: { id: job.projectId, userId: job.userId } })+ : null;+ if (!row) return "The project was deleted.";+ const doc = row.doc as unknown as ProjectDoc;+ const media = await completeMedia(job.userId, row.id);+ return {+ doc,+ name: `${doc.name} copy`,+ folderId: row.folderId,+ media,+ chats: [],+ added: mediaBytes(media),+ };+}++/** Re-check the job's viewer against the share at execution time — access+ * revoked between request and drain cancels the copy. */+async function viewerAllowed(share: ShareRow, viewerId: string): Promise<boolean> {+ if (share.access === "public" || share.userId === viewerId) return true;+ const user = await prisma.user.findUnique({+ where: { id: viewerId },+ select: { email: true },+ });+ const email = user?.email?.toLowerCase() ?? "";+ return (normalizeEmails(share.emails) ?? []).includes(email);+}++/** 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. */+async function enqueue(data: {+ kind: "share" | "duplicate";+ shareId?: string;+ projectId?: string;+ userId: string;+}): Promise<Response> {+ const job = await prisma.cutCopyJob.create({ data });+ const queued = await publishCopyJob(job.id);+ if (!queued) await executeCopyJob(job.id);+ return Response.json({ jobId: job.id });+}++/** Report a job's state. Also the self-heal path: a stale queued job+ * re-publishes its message, and a stale running job (crashed execution)+ * reports failure instead of spinning the poller forever. */+async function statusResponse(job: NonNullable<Awaited<ReturnType<typeof prisma.cutCopyJob.findFirst>>>) {+ const idleMs = Date.now() - job.updatedAt.getTime();+ if (job.state === "queued" && idleMs > STALE_QUEUED_MS) {+ await publishCopyJob(job.id);+ } else if (job.state === "running" && idleMs > STALE_RUNNING_MS) {+ await prisma.cutCopyJob.updateMany({+ where: { id: job.id, state: "running" },+ data: { state: "error", error: "The copy stalled — try again." },+ });+ job = (await prisma.cutCopyJob.findUnique({ where: { id: job.id } })) ?? job;+ }+ return Response.json({+ state: job.state,+ newProjectId: job.newProjectId ?? undefined,+ error: job.error ?? undefined,+ });+}++export const copyJobs = {+ /** A viewer asks to copy a share: quota is pre-checked for fast feedback+ * (the job checks again authoritatively), then the job queues. */+ async request(token: string, req: Request) {+ try {+ const view = await resolveShare(token, req);+ if (view instanceof Response) return view;+ const session = await auth.api.getSession({ headers: req.headers });+ if (!session?.user) return err("Sign in to copy this project.", 401);+ const plan = await copyPlan(view.share);+ if (!plan) return err("Project not found.", 404);+ const over = await quotaCheck(session.user.id, plan.added);+ if (over) return over;+ return await enqueue({ kind: "share", shareId: view.share.id, userId: session.user.id });+ } catch (e) {+ return caught(e, "Could not copy the project.");+ }+ },++ /** An owner duplicates their own project from the dashboard — same queue,+ * same pacing; only the source differs. */+ async requestDuplicate(userId: string, projectId: string) {+ try {+ const row = await prisma.cutProject.findFirst({ where: { id: projectId, userId } });+ if (!row) return err("Project not found.", 404);+ const media = await completeMedia(userId, projectId);+ const over = await quotaCheck(userId, mediaBytes(media));+ if (over) return over;+ return await enqueue({ kind: "duplicate", projectId, userId });+ } catch (e) {+ return caught(e, "Could not duplicate the project.");+ }+ },++ /** Poll a share copy (public namespace: share access re-checked). */+ async status(token: string, jobId: string, req: Request) {+ const view = await resolveShare(token, req);+ if (view instanceof Response) return view;+ const session = await auth.api.getSession({ headers: req.headers });+ if (!session?.user) return err("Sign in to copy this project.", 401);+ const job = await prisma.cutCopyJob.findFirst({+ where: { id: jobId, userId: session.user.id, shareId: view.share.id },+ });+ if (!job) return err("Copy not found.", 404);+ return statusResponse(job);+ },++ /** Poll any of the caller's own copy jobs (authed surface). */+ async ownerStatus(userId: string, jobId: string) {+ const job = await prisma.cutCopyJob.findFirst({ where: { id: jobId, userId } });+ if (!job) return err("Copy not found.", 404);+ return statusResponse(job);+ },+};++/** Execute one copy job (called by the queue consumer through+ * /api/cut-copy-worker). The kind picks the source — a share's filtered view+ * or the owner's own project — and the rest is one materialization path. 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 executeCopyJob(jobId: string): Promise<Response> {+ const claimed = await prisma.cutCopyJob.updateMany({+ where: { id: jobId, state: "queued" },+ data: { state: "running" },+ });+ // Already running, settled, or unknown — double delivery lands here.+ if (claimed.count === 0) return Response.json({ ok: true });++ const fail = async (message: string) => {+ await prisma.cutCopyJob.update({+ where: { id: jobId },+ data: { state: "error", error: message },+ });+ return Response.json({ ok: true });+ };++ try {+ const job = await prisma.cutCopyJob.findUnique({ where: { id: jobId } });+ if (!job) return Response.json({ ok: true });+ const src = job.kind === "duplicate" ? await duplicateSource(job) : await shareSource(job);+ if (typeof src === "string") return fail(src);+ const over = await quotaCheck(job.userId, src.added);+ if (over) return fail(QUOTA_MESSAGE);+ const now = Date.now();+ const copyDoc: ProjectDoc = { ...src.doc, name: src.name, createdAt: now, updatedAt: now };++ // The destination id is fixed up front and recorded before any bytes move,+ // so a retry reuses it: the R2 keys are the same, and the project create+ // below lands under the same id instead of minting a second project.+ const newProjectId = job.newProjectId ?? randomUUID();+ if (!job.newProjectId) {+ await prisma.cutCopyJob.update({ where: { id: jobId }, data: { newProjectId } });+ }++ // R2 copies run before the transaction (network I/O can't sit inside one)+ // but are idempotent: same source to the same deterministic destination+ // key, so a redelivery just overwrites with identical bytes.+ for (const m of src.media) {+ await copy(m.r2Key, projectMediaKey(job.userId, newProjectId, m.fileName));+ }++ // One transaction for every row and the usage counter AND the job's+ // terminal state. Because the claim above requires state=queued and this+ // commit flips it to done atomically, the whole body commits at most once:+ // addUsage never double-counts, a failure rolls the project back (no+ // orphan row), and a retry re-runs from a clean slate. Only already-copied+ // R2 bytes can linger on a permanent failure, and those are GC-collectible+ // under a projectId no row references.+ await prisma.$transaction(async (tx) => {+ await tx.cutProject.create({+ data: {+ id: newProjectId,+ userId: job.userId,+ name: copyDoc.name,+ doc: copyDoc as unknown as Prisma.InputJsonValue,+ folderId: src.folderId,+ },+ });+ if (src.media.length > 0) {+ await tx.cutMediaObject.createMany({+ data: src.media.map((m) => ({+ userId: job.userId,+ projectId: newProjectId,+ r2Key: projectMediaKey(job.userId, newProjectId, m.fileName),+ fileName: m.fileName,+ mime: m.mime,+ bytes: m.bytes,+ kind: "media",+ uploadState: "complete",+ })),+ });+ }+ if (src.chats.length > 0) {+ // Thread ids are client-generated and keyed (projectId, id), so the+ // copies keep their ids under the new project.+ await tx.cutChatThread.createMany({+ data: src.chats.map((c) => ({+ projectId: newProjectId,+ id: c.id,+ userId: job.userId,+ data: c.data as Prisma.InputJsonValue,+ })),+ });+ }+ await addUsage(tx, job.userId, src.added);+ await tx.cutCopyJob.update({+ where: { id: jobId },+ data: { state: "done", newProjectId },+ });+ });+ return Response.json({ ok: true });+ } catch (e) {+ // Transient failure (database or R2 hiccup): release the claim so the+ // queue's retry can run the job again. The recorded newProjectId makes the+ // retry reuse the same destination.+ await prisma.cutCopyJob+ .updateMany({ where: { id: jobId, state: "running" }, data: { state: "queued" } })+ .catch(() => {});+ return err(e instanceof Error ? e.message : "Copy failed.", 500);+ }+}diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.tsindex 288005cf..0d7af57a 100644--- a/site/src/cut/server/cloud/projects.ts+++ b/site/src/cut/server/cloud/projects.ts@@ -4,7 +4,6 @@ import type { ProjectDoc, ProjectFolder, ProjectSummary } from "@/cut/lib/types"import type { Prisma } from "@/generated/prisma/client";import { prisma } from "@/lib/prisma";import {- copy,del,presignGet,projectExportKey,@@ -220,6 +219,7 @@ export const projectsCloud = {await prisma.$transaction(async (tx) => {await tx.cutMediaObject.deleteMany({ where: { userId, projectId: id } });await tx.cutChatThread.deleteMany({ where: { userId, projectId: id } });+ await tx.cutProjectShare.deleteMany({ where: { projectId: id } });await tx.cutProject.delete({ where: { id } });await addUsage(tx, userId, -freed);});@@ -230,48 +230,6 @@ export const projectsCloud = {}},- /** Duplicate a project: copy the doc and its media objects (not its exports)- * into a fresh project. */- async duplicate(userId: string, id: string) {- try {- const row = await getProject(userId, id);- if (!row) return err("Project not found.", 404);- const doc = docOf(row);- const now = Date.now();- const copyDoc: ProjectDoc = { ...doc, name: `${doc.name} copy`, createdAt: now, updatedAt: now };- const media = await prisma.cutMediaObject.findMany({- where: { userId, projectId: id, kind: "media", uploadState: "complete" },- });- const created = await prisma.cutProject.create({- data: { userId, name: copyDoc.name, doc: asJson(copyDoc), folderId: row.folderId },- });- for (const m of media) {- await copy(m.r2Key, projectMediaKey(userId, created.id, m.fileName));- }- const added = media.reduce((sum, m) => sum + Number(m.bytes), 0);- await prisma.$transaction(async (tx) => {- if (media.length > 0) {- await tx.cutMediaObject.createMany({- data: media.map((m) => ({- userId,- projectId: created.id,- r2Key: projectMediaKey(userId, created.id, m.fileName),- fileName: m.fileName,- mime: m.mime,- bytes: m.bytes,- kind: "media",- uploadState: "complete",- })),- });- }- await addUsage(tx, userId, added);- });- return Response.json(summarize(created, added));- } catch (e) {- return caught(e, "Could not duplicate project.");- }- },-async move(userId: string, id: string, req: Request) {try {const { folderId } = (await req.json()) as { folderId: string | null };diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.tsindex 125c190d..c4a70bb0 100644--- a/site/src/cut/server/cloud/routes.ts+++ b/site/src/cut/server/cloud/routes.ts@@ -8,11 +8,13 @@ import { type DonkeyAuthenticatedRequest, isDonkeySuperUser } from "@/lib/donkeyimport { matchRouteTable, type RouteEntry } from "../http/match";import { captionsCloud } from "./captions";import { chatsCloud } from "./chats";+import { copyJobs } from "./copyQueue";import { runGc } from "./gc";import { jobsCloud } from "./jobs";import { libraryCloud } from "./library";import { mediaCloud } from "./media";import { projectsCloud } from "./projects";+import { shareCloud } from "./share";import { transcribeCloud } from "./transcribe";import { usageApi } from "./usage";@@ -37,13 +39,17 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "GET", path: "/api/cut-cloud/projects/:id", handler: (_r, u, p) => projectsCloud.get(u, p.id) },{ method: "PUT", path: "/api/cut-cloud/projects/:id", handler: (r, u, p) => projectsCloud.put(u, p.id, r) },{ method: "DELETE", path: "/api/cut-cloud/projects/:id", handler: (_r, u, p) => projectsCloud.remove(u, p.id) },- { method: "POST", path: "/api/cut-cloud/projects/:id/duplicate", handler: (_r, u, p) => projectsCloud.duplicate(u, p.id) },+ { method: "POST", path: "/api/cut-cloud/projects/:id/duplicate", handler: (_r, u, p) => copyJobs.requestDuplicate(u, p.id) },+ { method: "GET", path: "/api/cut-cloud/copy-jobs/:jobId", handler: (_r, u, p) => copyJobs.ownerStatus(u, p.jobId) },{ method: "GET", path: "/api/cut-cloud/projects/:id/exports", handler: (_r, u, p) => projectsCloud.listExports(u, p.id) },{ method: "GET", path: "/api/cut-cloud/projects/:id/exports/:file", handler: (r, u, p) => projectsCloud.serveExport(u, p.id, p.file, new URL(r.url).searchParams.has("download")) },{ method: "DELETE", path: "/api/cut-cloud/projects/:id/exports/:file", handler: (_r, u, p) => projectsCloud.removeExport(u, p.id, p.file) },{ method: "GET", path: "/api/cut-cloud/projects/:id/media/:file", handler: (_r, u, p) => projectsCloud.serveMedia(u, p.id, p.file) },{ method: "DELETE", path: "/api/cut-cloud/projects/:id/media/:file", handler: (_r, u, p) => projectsCloud.removeMedia(u, p.id, p.file) },{ method: "GET", path: "/api/cut-cloud/projects/:id/preview", handler: (_r, u, p) => projectsCloud.servePreview(u, p.id) },+ { method: "GET", path: "/api/cut-cloud/projects/:id/share", handler: (_r, u, p) => shareCloud.get(u, p.id) },+ { method: "PUT", path: "/api/cut-cloud/projects/:id/share", handler: (r, u, p) => shareCloud.put(u, p.id, r) },+ { method: "DELETE", path: "/api/cut-cloud/projects/:id/share", handler: (_r, u, p) => shareCloud.remove(u, p.id) },{ method: "GET", path: "/api/cut-cloud/projects/:id/chats", handler: (_r, u, p) => chatsCloud.list(u, p.id) },{ method: "PUT", path: "/api/cut-cloud/projects/:id/chats/:chatId", handler: (r, u, p) => chatsCloud.put(u, p.id, p.chatId, r) },{ method: "DELETE", path: "/api/cut-cloud/projects/:id/chats/:chatId", handler: (_r, u, p) => chatsCloud.remove(u, p.id, p.chatId) },diff --git a/site/src/cut/server/cloud/sharedRoutes.ts b/site/src/cut/server/cloud/sharedRoutes.tsnew file mode 100644index 00000000..00b67b83--- /dev/null+++ b/site/src/cut/server/cloud/sharedRoutes.ts@@ -0,0 +1,43 @@+// The public shared-viewer API surface, namespaced under /api/cut-shared/*.+// Paths mirror the engine table after the token segment so the client's shared+// driver is a pure prefix rewrite of /api/cut/*. There is no auth wrapper:+// access is decided per request by the share row (public, or a signed-in+// invitee) inside sharedView's resolver.+import { matchRouteTable, type RouteEntry } from "../http/match";+import { copyJobs } from "./copyQueue";+import { sharedView } from "./sharedView";++type SharedHandler = (req: Request, params: Record<string, string>) => Promise<Response>;++interface SharedRoute extends RouteEntry {+ handler: SharedHandler;+}++const CUT_SHARED_ROUTES: SharedRoute[] = [+ { method: "GET", path: "/api/cut-shared/:token", handler: (r, p) => sharedView.meta(p.token, r) },+ { method: "GET", path: "/api/cut-shared/:token/projects/:id", handler: (r, p) => sharedView.doc(p.token, p.id, r) },+ { method: "GET", path: "/api/cut-shared/:token/projects/:id/media/:file", handler: (r, p) => sharedView.serveMedia(p.token, p.id, p.file, r) },+ { method: "POST", path: "/api/cut-shared/:token/media/presign-get", handler: (r, p) => sharedView.presignGetBatch(p.token, r) },+ { method: "GET", path: "/api/cut-shared/:token/projects/:id/chats", handler: (r, p) => sharedView.chats(p.token, p.id, r) },+ { method: "GET", path: "/api/cut-shared/:token/projects/:id/preview", handler: (r, p) => sharedView.preview(p.token, p.id, r) },+ { method: "POST", path: "/api/cut-shared/:token/copy", handler: (r, p) => copyJobs.request(p.token, r) },+ { method: "GET", path: "/api/cut-shared/:token/copy/:jobId", handler: (r, p) => copyJobs.status(p.token, p.jobId, r) },+];++export async function cutSharedCatchAll(req: Request): Promise<Response> {+ const { pathname } = new URL(req.url);+ const match = matchRouteTable(CUT_SHARED_ROUTES, req.method, pathname);+ if (!match) return new Response("Not found.", { status: 404 });+ if ("methodNotAllowed" in match) {+ return new Response("Method not allowed.", {+ status: 405,+ headers: { Allow: match.methodNotAllowed.join(", ") },+ });+ }+ const res = await match.route.handler(req, match.params);+ if (match.head && res.body) {+ void res.body.cancel();+ return new Response(null, { status: res.status, headers: res.headers });+ }+ return res;+}diff --git a/site/src/cut/worker/README.md b/site/src/cut/worker/README.mdindex c0c476a0..5f2f4628 100644--- a/site/src/cut/worker/README.md+++ b/site/src/cut/worker/README.md@@ -72,3 +72,23 @@ Manual deploy from `site/`:```shnpm run worker:build && npx wrangler deploy -c src/cut/worker/wrangler.jsonc```++## Copy queue++The Worker is also the consumer of the `donkey-cut-copy` Cloudflare Queue:+project copies — a viewer copying a share, or an owner duplicating a cloud+project from the dashboard — enqueue a `CutCopyJob` id, and the consumer+POSTs each id back to the hosted `/api/cut-copy-worker` endpoint one message+at a time (`max_batch_size` and `max_concurrency` are both 1), so copies+drain serially instead of stampeding R2. One-time setup:++1. Create the queue (from `site/`): `npx wrangler queues create donkey-cut-copy`.+2. Worker secrets: `CUT_COPY_EXECUTE_URL` (the hosted endpoint, e.g.+ `https://donkeycut.com/api/cut-copy-worker`) and `CUT_COPY_EXECUTE_SECRET`+ (any long random string).+3. On the hosted site (Vercel env): `CLOUDFLARE_QUEUES_API_TOKEN` (an API+ token with Queues edit on the account — publishes ride the REST API since+ the site isn't a Worker) and the same `CUT_COPY_EXECUTE_SECRET`.++Without the queue env, the hosted API runs copies inline in the request —+fine for local dev, unthrottled in production.diff --git a/site/src/cut/worker/cf/worker.ts b/site/src/cut/worker/cf/worker.tsindex 059be546..33050b48 100644--- a/site/src/cut/worker/cf/worker.ts+++ b/site/src/cut/worker/cf/worker.ts@@ -14,8 +14,19 @@ type WorkerEnv = {R2_ACCESS_KEY_ID: string;R2_SECRET_ACCESS_KEY: string;CUT_WAKE_SECRET: string;+ CUT_COPY_EXECUTE_URL: string;+ CUT_COPY_EXECUTE_SECRET: string;};+// Minimal shapes for the queue consumer — this file stays off workers-types+// on purpose (see the header note).+type QueueMessage = {+ body: unknown;+ ack(): void;+ retry(opts?: { delaySeconds?: number }): void;+};+type QueueBatch = { messages: QueueMessage[] };+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).@@ -50,4 +61,33 @@ export default {}return new Response("donkey-cut-worker", { status: 200 });},++ // Share-copy queue consumer (donkey-cut-copy, wrangler.jsonc): one message+ // per batch, one batch at a time, so copies drain serially no matter how+ // many viewers ask at once. The copy itself runs on the hosted API — this+ // handler only paces it and carries the queue's retry semantics: 2xx acks,+ // anything else redelivers after a delay.+ async queue(batch: QueueBatch, env: WorkerEnv): Promise<void> {+ for (const message of batch.messages) {+ const jobId = (message.body as { jobId?: unknown } | null)?.jobId;+ if (typeof jobId !== "string" || !jobId) {+ message.ack();+ continue;+ }+ try {+ const res = await fetch(env.CUT_COPY_EXECUTE_URL, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${env.CUT_COPY_EXECUTE_SECRET}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ jobId }),+ });+ if (res.ok) message.ack();+ else message.retry({ delaySeconds: 30 });+ } catch {+ message.retry({ delaySeconds: 30 });+ }+ }+ },};diff --git a/site/src/cut/worker/wrangler.jsonc b/site/src/cut/worker/wrangler.jsoncindex 54f4889a..d46a45f8 100644--- a/site/src/cut/worker/wrangler.jsonc+++ b/site/src/cut/worker/wrangler.jsonc@@ -25,5 +25,19 @@"durable_objects": {"bindings": [{ "name": "CUT_RENDER_WORKER", "class_name": "CutRenderWorker" }]},- "migrations": [{ "tag": "v1", "new_sqlite_classes": ["CutRenderWorker"] }]+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["CutRenderWorker"] }],+ // Share-copy jobs drain serially: one message per batch, one batch in+ // flight, so a burst of copy requests can't stampede R2 or the database.+ // Create the queue once: npx wrangler queues create donkey-cut-copy+ "queues": {+ "consumers": [+ {+ "queue": "donkey-cut-copy",+ "max_batch_size": 1,+ "max_concurrency": 1,+ "max_retries": 10,+ "retry_delay": 30+ }+ ]+ }}