Skip to content

Open source CapCut alternative.

TypeScript

fix(site): reclaim orphaned cloud project media

David Leb4834aca0b39
diff --git a/site/src/cut/server/cloud/gc.ts b/site/src/cut/server/cloud/gc.ts
index 6113a685..50ff3669 100644
--- a/site/src/cut/server/cloud/gc.ts
+++ b/site/src/cut/server/cloud/gc.ts
@@ -1,10 +1,13 @@
-// Storage garbage collection: presigned-but-never-completed media objects and
-// long-terminal render jobs. Runs from the Vercel daily cron (vercel.json) or
-// a superuser hitting GET /api/cut-cloud/gc.
+// Storage garbage collection: presigned-but-never-completed media objects,
+// project media no doc references, and long-terminal render jobs. Runs from
+// the Vercel daily cron (vercel.json) or a superuser hitting
+// GET /api/cut-cloud/gc.
import { prisma } from "@/lib/prisma";
import { del } from "./r2";
+import { addUsage } from "./usage";
const PENDING_MAX_AGE_MS = 24 * 60 * 60 * 1000;
+const ORPHAN_MAX_AGE_MS = 24 * 60 * 60 * 1000;
const JOB_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
const TERMINAL_STATES = ["done", "error", "canceled"];
@@ -23,6 +26,47 @@ export async function runGc(): Promise<Response> {
where: { id: { in: pending.map((o) => o.id) } },
});
}
+ // Unreferenced project media: bytes a worker or client landed in a project
+ // whose doc never adopted them — an abandoned import, a tab closed before
+ // the save. The doc is the sole owner of project media, adoption happens
+ // within seconds of landing, and the one delayed delivery path (the cloud
+ // import poll) caps at ten minutes — so after a day of grace, unreferenced
+ // means garbage. Docs of deleted projects are gone too, which orphans (and
+ // sweeps) any rows their deletion missed.
+ const mediaCandidates = await prisma.cutMediaObject.findMany({
+ where: {
+ kind: "media",
+ uploadState: "complete",
+ projectId: { not: null },
+ updatedAt: { lt: new Date(Date.now() - ORPHAN_MAX_AGE_MS) },
+ },
+ select: { id: true, userId: true, projectId: true, fileName: true, r2Key: true, bytes: true },
+ });
+ const docProjects = await prisma.cutProject.findMany({
+ where: { id: { in: [...new Set(mediaCandidates.map((c) => c.projectId!))] } },
+ select: { id: true, doc: true },
+ });
+ const referenced = new Map(
+ docProjects.map((p) => {
+ const assets = (p.doc as { assets?: { fileName?: string }[] } | null)?.assets ?? [];
+ return [p.id, new Set(assets.map((a) => a.fileName))];
+ })
+ );
+ const orphans = mediaCandidates.filter((c) => !referenced.get(c.projectId!)?.has(c.fileName));
+ const byUser = new Map<string, typeof orphans>();
+ for (const o of orphans) {
+ const list = byUser.get(o.userId) ?? [];
+ list.push(o);
+ byUser.set(o.userId, list);
+ }
+ for (const [userId, rows] of byUser) {
+ await prisma.$transaction(async (tx) => {
+ await tx.cutMediaObject.deleteMany({ where: { id: { in: rows.map((r) => r.id) } } });
+ await addUsage(tx, userId, -rows.reduce((sum, r) => sum + Number(r.bytes), 0));
+ });
+ await del(rows.map((r) => r.r2Key));
+ }
+
// Old terminal jobs go together with their overlay PNGs — the worker deletes
// overlays when it settles a job, but a job canceled while still queued was
// never claimed, so its overlays only die here.
@@ -45,5 +89,9 @@ export async function runGc(): Promise<Response> {
oldJobs.length > 0
? await prisma.cutRenderJob.deleteMany({ where: { id: { in: oldJobs.map((j) => j.id) } } })
: { count: 0 };
- return Response.json({ pendingObjects: pending.length, renderJobs: jobs.count });
+ return Response.json({
+ pendingObjects: pending.length,
+ orphanedMedia: orphans.length,
+ renderJobs: jobs.count,
+ });
}
diff --git a/site/src/cut/worker/db.ts b/site/src/cut/worker/db.ts
index 0f90c7ab..07f1067b 100644
--- a/site/src/cut/worker/db.ts
+++ b/site/src/cut/worker/db.ts
@@ -54,3 +54,31 @@ export async function registerObject(opts: {
}),
]);
}
+
+/**
+ * Undo registerObject for a job's staged files: drop the rows and hand the
+ * bytes back to the user's storage total. R2 object deletion is the caller's
+ * (best-effort) follow-up.
+ */
+export async function unregisterObjects(userId: string, r2Keys: string[]): Promise<void> {
+ if (r2Keys.length === 0) return;
+ const rows = await prisma.cutMediaObject.findMany({
+ where: { userId, r2Key: { in: r2Keys } },
+ select: { id: true, bytes: true, uploadState: true },
+ });
+ if (rows.length === 0) return;
+ const bytes = rows.reduce(
+ (sum, r) => (r.uploadState === "complete" ? sum + Number(r.bytes) : sum),
+ 0
+ );
+ await prisma.$transaction(async (tx) => {
+ await tx.cutMediaObject.deleteMany({ where: { id: { in: rows.map((r) => r.id) } } });
+ const usage = await tx.cutStorageUsage.findUnique({ where: { userId } });
+ const next = Math.max(0, (usage ? Number(usage.bytes) : 0) - bytes);
+ await tx.cutStorageUsage.upsert({
+ where: { userId },
+ create: { userId, bytes: BigInt(next) },
+ update: { bytes: BigInt(next) },
+ });
+ });
+}
diff --git a/site/src/cut/worker/importUrlJob.ts b/site/src/cut/worker/importUrlJob.ts
index 3b14294b..bb5bab26 100644
--- a/site/src/cut/worker/importUrlJob.ts
+++ b/site/src/cut/worker/importUrlJob.ts
@@ -2,8 +2,8 @@ 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";
+import { prisma, registerObject, unregisterObjects, type ClaimedJob } from "./db";
+import { deleteObjects, 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. */
@@ -47,23 +47,35 @@ export async function runImportUrlJob(
});
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 });
+ // A failed or canceled run keeps no bytes: whatever it staged in R2 is
+ // unregistered and deleted before the error propagates, so the project's
+ // storage only ever holds media the client can still adopt.
+ const staged: string[] = [];
+ try {
+ for (const f of dl.files) {
+ if (isCanceled()) throw new Error("Import canceled.");
+ const fileName = dedupeName(path.basename(f.file), taken);
+ taken.add(fileName);
+ const key = mediaKey(job.userId, projectId, fileName);
+ staged.push(key);
+ 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 } : {}) };
+ } catch (err) {
+ await unregisterObjects(job.userId, staged).catch(() => {});
+ await deleteObjects(staged);
+ throw err;
}
- return { files, ...(dl.text ? { text: dl.text } : {}) };
} finally {
void rm(tmp, { recursive: true, force: true });
}