Skip to content

Open source CapCut alternative.

TypeScript

feat(site): reclaim lapsed-subscription storage after a grace window

David Lea8655c011923
diff --git a/site/src/cut/server/cloud/gc.ts b/site/src/cut/server/cloud/gc.ts
index 50ff3669..89539215 100644
--- a/site/src/cut/server/cloud/gc.ts
+++ b/site/src/cut/server/cloud/gc.ts
@@ -1,8 +1,13 @@
// Storage garbage collection: presigned-but-never-completed media objects,
-// project media no doc references, and long-terminal render jobs. Runs from
+// project media no doc references, long-terminal render jobs, and storage
+// reclamation for lapsed subscriptions past their grace window. Runs from
// the Vercel daily cron (vercel.json) or a superuser hitting
// GET /api/cut-cloud/gc.
import { prisma } from "@/lib/prisma";
+import { graceDeadline } from "./grace";
+import { cutLimitsFor, FREE_STORAGE_BYTES } from "./limits";
+import { deleteLibraryAssetCascade } from "./library";
+import { deleteProjectCascade } from "./projects";
import { del } from "./r2";
import { addUsage } from "./usage";
@@ -10,6 +15,151 @@ 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"];
+// Reclamation converges over daily runs rather than risking one long one.
+const RECLAIM_SCAN_LIMIT = 500;
+const RECLAIM_MAX_USERS = 10;
+const RECLAIM_MAX_DELETES_PER_USER = 25;
+
+type ReclaimPlan = { projects: string[]; assets: string[]; bytes: number };
+
+/** What the sweep can actually free for one account, oldest first: whole
+ * projects, then library assets, stopping as soon as the plan covers `target`.
+ * Sizes come from the media rows themselves, so a drifted usage counter can
+ * never widen a deletion, and anything that would free nothing is left out —
+ * it costs the user their work and buys no space. */
+async function reclaimPlan(userId: string, target: number): Promise<ReclaimPlan> {
+ const plan: ReclaimPlan = { projects: [], assets: [], bytes: 0 };
+ const projects = await prisma.cutProject.findMany({
+ where: { userId },
+ orderBy: { updatedAt: "asc" },
+ select: { id: true },
+ });
+ const sums = await prisma.cutMediaObject.groupBy({
+ by: ["projectId"],
+ where: {
+ userId,
+ projectId: { in: projects.map((p) => p.id) },
+ uploadState: "complete",
+ },
+ _sum: { bytes: true },
+ });
+ const projectBytes = new Map(sums.map((s) => [s.projectId as string, Number(s._sum.bytes ?? 0)]));
+ for (const p of projects) {
+ if (plan.bytes >= target) return plan;
+ const size = projectBytes.get(p.id) ?? 0;
+ if (size <= 0) continue;
+ plan.projects.push(p.id);
+ plan.bytes += size;
+ }
+
+ const assets = await prisma.cutLibraryAsset.findMany({
+ where: { userId },
+ orderBy: { createdAt: "asc" },
+ select: { id: true, mediaObjectId: true },
+ });
+ const objects = await prisma.cutMediaObject.findMany({
+ where: {
+ userId,
+ uploadState: "complete",
+ id: { in: assets.map((a) => a.mediaObjectId) },
+ },
+ select: { id: true, bytes: true },
+ });
+ const assetBytes = new Map(objects.map((o) => [o.id, Number(o.bytes)]));
+ for (const a of assets) {
+ if (plan.bytes >= target) break;
+ const size = assetBytes.get(a.mediaObjectId) ?? 0;
+ if (size <= 0) continue;
+ plan.assets.push(a.id);
+ plan.bytes += size;
+ }
+ return plan;
+}
+
+/** Bring accounts whose Pro ended and whose grace window has passed back under
+ * the free storage cap: least-recently-updated projects first, then the oldest
+ * library assets. The plan is built and checked before anything is deleted, so
+ * an account whose overage the sweep cannot reach is reported rather than
+ * emptied, and content under the cap is never touched. */
+async function reclaimOverQuota() {
+ const out = {
+ users: 0,
+ projects: 0,
+ libraryAssets: 0,
+ bytes: 0,
+ // Left for tomorrow by the per-run caps: a truncated sweep has to look
+ // truncated in the summary, not finished.
+ deferred: 0,
+ // Over the cap with nothing worth deleting — needs a human, not a sweep.
+ unreclaimable: 0,
+ failed: 0,
+ };
+ const overCap = await prisma.cutStorageUsage.findMany({
+ where: { bytes: { gt: BigInt(FREE_STORAGE_BYTES) } },
+ orderBy: { bytes: "desc" },
+ take: RECLAIM_SCAN_LIMIT,
+ select: { userId: true },
+ });
+ if (overCap.length === 0) return out;
+ // One read for the whole batch: most accounts over the free cap are paying
+ // ones the sweep will never touch, and they are not worth a query each.
+ const subs = await prisma.proSubscription.findMany({
+ where: { userId: { in: overCap.map((r) => r.userId) } },
+ select: { userId: true, status: true, currentPeriodEnd: true },
+ });
+ const now = Date.now();
+ const lapsed = subs.filter((s) => {
+ const deadline = graceDeadline(s);
+ return deadline !== null && now >= deadline.getTime();
+ });
+
+ for (const { userId } of lapsed) {
+ if (out.users >= RECLAIM_MAX_USERS) {
+ out.deferred += 1;
+ continue;
+ }
+ try {
+ // Re-read the tier: a superuser flag or a resubscribe since the scan
+ // takes the account back out of reach.
+ const limits = await cutLimitsFor(userId);
+ if (limits.storageBytes === null || limits.storageBytes > FREE_STORAGE_BYTES) continue;
+ const stored = await prisma.cutMediaObject.aggregate({
+ where: { userId, uploadState: "complete" },
+ _sum: { bytes: true },
+ });
+ const target = Number(stored._sum.bytes ?? 0) - limits.storageBytes;
+ if (target <= 0) continue;
+
+ const plan = await reclaimPlan(userId, target);
+ if (plan.bytes < target) {
+ out.unreclaimable += 1;
+ continue;
+ }
+ out.users += 1;
+ let budget = RECLAIM_MAX_DELETES_PER_USER;
+ for (const projectId of plan.projects) {
+ if (budget <= 0) break;
+ out.bytes += await deleteProjectCascade(userId, projectId);
+ out.projects += 1;
+ budget -= 1;
+ }
+ for (const assetId of plan.assets) {
+ if (budget <= 0) break;
+ out.bytes += (await deleteLibraryAssetCascade(userId, assetId)) ?? 0;
+ out.libraryAssets += 1;
+ budget -= 1;
+ }
+ if (plan.projects.length + plan.assets.length > RECLAIM_MAX_DELETES_PER_USER) {
+ out.deferred += 1;
+ }
+ } catch {
+ // One account's failure — a project deleted underneath us, an R2 blip —
+ // must not stop the sweep or fail the cron.
+ out.failed += 1;
+ }
+ }
+ return out;
+}
export async function runGc(): Promise<Response> {
const pending = await prisma.cutMediaObject.findMany({
@@ -89,9 +239,19 @@ export async function runGc(): Promise<Response> {
oldJobs.length > 0
? await prisma.cutRenderJob.deleteMany({ where: { id: { in: oldJobs.map((j) => j.id) } } })
: { count: 0 };
+
+ const reclaimed = await reclaimOverQuota();
+
return Response.json({
pendingObjects: pending.length,
orphanedMedia: orphans.length,
renderJobs: jobs.count,
+ reclaimedUsers: reclaimed.users,
+ reclaimedProjects: reclaimed.projects,
+ reclaimedLibraryAssets: reclaimed.libraryAssets,
+ reclaimedBytes: reclaimed.bytes,
+ reclaimDeferredUsers: reclaimed.deferred,
+ reclaimUnreclaimableUsers: reclaimed.unreclaimable,
+ reclaimFailedUsers: reclaimed.failed,
});
}
diff --git a/site/src/cut/server/cloud/grace.ts b/site/src/cut/server/cloud/grace.ts
new file mode 100644
index 00000000..a4b4b6c6
--- /dev/null
+++ b/site/src/cut/server/cloud/grace.ts
@@ -0,0 +1,43 @@
+// A Pro subscription that ends can leave more bytes in R2 than the free tier
+// holds. Those accounts get a grace window before the daily sweep reclaims
+// storage down to the free cap (gc.ts); the usage API surfaces the same state
+// so the client can warn first.
+import { isActiveProStatus } from "@/lib/billing/pro-subscription";
+import { prisma } from "@/lib/prisma";
+import { FREE_STORAGE_BYTES, type CutLimits } from "./limits";
+
+const GRACE_MS = 30 * 24 * 60 * 60 * 1000;
+
+// Reclamation never fires before this date + grace, so accounts whose Pro
+// ended long before the sweep existed still get a full warning window.
+const RECLAIM_EPOCH_MS = Date.UTC(2026, 6, 26);
+
+type SubscriptionAnchor = { status: string; currentPeriodEnd: Date | null };
+
+/** When a lapsed subscription's storage becomes reclaimable, or null when the
+ * subscription is not one we count as ended. Dunning is not churn: while
+ * Stripe is still retrying the invoice (`past_due`) a recovered card puts the
+ * account straight back on Pro, so the deletion clock has not started. */
+export function graceDeadline(sub: SubscriptionAnchor): Date | null {
+ if (!sub.currentPeriodEnd || isActiveProStatus(sub.status) || sub.status === "past_due") {
+ return null;
+ }
+ return new Date(Math.max(sub.currentPeriodEnd.getTime(), RECLAIM_EPOCH_MS) + GRACE_MS);
+}
+
+/** Non-null when the account is out of Pro, over the free cap, and anchored to
+ * an ended subscription. The caller supplies current usage and limits so one
+ * read serves both this check and its own response. */
+export async function graceState(
+ userId: string,
+ bytes: number,
+ limits: CutLimits
+): Promise<{ deadline: Date; overBytes: number } | null> {
+ // Anyone whose quota exceeds the free cap (Pro, superuser) is not in grace.
+ if (limits.storageBytes === null || limits.storageBytes > FREE_STORAGE_BYTES) return null;
+ if (bytes <= FREE_STORAGE_BYTES) return null;
+ const sub = await prisma.proSubscription.findUnique({ where: { userId } });
+ const deadline = sub ? graceDeadline(sub) : null;
+ if (!deadline) return null;
+ return { deadline, overBytes: bytes - FREE_STORAGE_BYTES };
+}
diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.ts
index bcb5ea31..a751ebfe 100644
--- a/site/src/cut/server/cloud/library.ts
+++ b/site/src/cut/server/cloud/library.ts
@@ -140,6 +140,30 @@ async function copyIntoLibrary(
return dest;
}
+/** Delete a library asset with its media object, bytes, and R2 key. Returns
+ * bytes freed, or null when the asset is not this user's. Shared by the delete
+ * route and the storage-reclamation sweep (gc.ts). */
+export async function deleteLibraryAssetCascade(
+ userId: string,
+ id: string
+): Promise<number | null> {
+ const asset = await prisma.cutLibraryAsset.findFirst({ where: { id, userId } });
+ if (!asset) return null;
+ const obj = await prisma.cutMediaObject.findFirst({
+ where: { id: asset.mediaObjectId, userId },
+ });
+ const freed = obj && obj.uploadState === "complete" ? Number(obj.bytes) : 0;
+ await prisma.$transaction(async (tx) => {
+ await tx.cutLibraryAsset.delete({ where: { id } });
+ if (obj) {
+ await tx.cutMediaObject.delete({ where: { id: obj.id } });
+ if (freed > 0) await addUsage(tx, userId, -freed);
+ }
+ });
+ if (obj) await del([obj.r2Key]);
+ return freed;
+}
+
/** Copy one library object into a project, recording the row and usage.
* Returns the fileName inside the project. */
async function copyIntoProject(
@@ -367,17 +391,8 @@ export const libraryCloud = {
async remove(userId: string, id: string) {
try {
- const asset = await prisma.cutLibraryAsset.findFirst({ where: { id, userId } });
- if (!asset) throw new Error("Library asset not found.");
- const obj = await prisma.cutMediaObject.findUnique({ where: { id: asset.mediaObjectId } });
- await prisma.$transaction(async (tx) => {
- await tx.cutLibraryAsset.delete({ where: { id } });
- if (obj) {
- await tx.cutMediaObject.delete({ where: { id: obj.id } });
- if (obj.uploadState === "complete") await addUsage(tx, userId, -Number(obj.bytes));
- }
- });
- if (obj) await del([obj.r2Key]);
+ const freed = await deleteLibraryAssetCascade(userId, id);
+ if (freed === null) throw new Error("Library asset not found.");
return Response.json({ ok: true });
} catch (e) {
return caught(e, "Could not delete.");
diff --git a/site/src/cut/server/cloud/limits.ts b/site/src/cut/server/cloud/limits.ts
index d7e10caa..27b7811e 100644
--- a/site/src/cut/server/cloud/limits.ts
+++ b/site/src/cut/server/cloud/limits.ts
@@ -10,7 +10,9 @@ export type CutLimits = {
renderJobsPerDay: number | null;
};
-const FREE: CutLimits = { storageBytes: 250 * 1024 ** 2, renderJobsPerDay: 10 };
+export const FREE_STORAGE_BYTES = 250 * 1024 ** 2;
+
+const FREE: CutLimits = { storageBytes: FREE_STORAGE_BYTES, renderJobsPerDay: 10 };
const PRO: CutLimits = { storageBytes: 50 * 1024 ** 3, renderJobsPerDay: 200 };
const UNLIMITED: CutLimits = { storageBytes: null, renderJobsPerDay: null };
diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.ts
index b52abf08..dd84d313 100644
--- a/site/src/cut/server/cloud/projects.ts
+++ b/site/src/cut/server/cloud/projects.ts
@@ -87,6 +87,35 @@ async function projectSizes(userId: string, projectIds: string[]): Promise<Map<s
const asJson = (doc: ProjectDoc) => doc as unknown as Prisma.InputJsonValue;
+/** Delete a project and everything hanging off it — media rows and bytes,
+ * chats, shares — and settle the usage counter. Returns bytes freed. Shared by
+ * the delete route and the storage-reclamation sweep (gc.ts). */
+export async function deleteProjectCascade(userId: string, id: string): Promise<number> {
+ const objects = await prisma.cutMediaObject.findMany({
+ where: { userId, projectId: id },
+ });
+ const freed = objects
+ .filter((o) => o.uploadState === "complete")
+ .reduce((sum, o) => sum + Number(o.bytes), 0);
+ // Cancel the project's in-flight renders first: a job finishing after
+ // the delete would re-register storage for a project nothing can see.
+ await prisma.cutRenderJob.updateMany({
+ where: { userId, projectId: id, state: { in: ["queued", "running"] } },
+ data: { state: "canceled" },
+ });
+ 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 } });
+ // deleteMany, so ownership is enforced here rather than trusted from the
+ // caller: a mismatched (userId, id) pair deletes nothing.
+ await tx.cutProject.deleteMany({ where: { id, userId } });
+ await addUsage(tx, userId, -freed);
+ });
+ await del(objects.map((o) => o.r2Key));
+ return freed;
+}
+
export const projectsCloud = {
async list(userId: string) {
const rows = await prisma.cutProject.findMany({
@@ -204,26 +233,7 @@ export const projectsCloud = {
try {
const row = await getProject(userId, id);
if (!row) return err("Project not found.", 404);
- const objects = await prisma.cutMediaObject.findMany({
- where: { userId, projectId: id },
- });
- const freed = objects
- .filter((o) => o.uploadState === "complete")
- .reduce((sum, o) => sum + Number(o.bytes), 0);
- // Cancel the project's in-flight renders first: a job finishing after
- // the delete would re-register storage for a project nothing can see.
- await prisma.cutRenderJob.updateMany({
- where: { userId, projectId: id, state: { in: ["queued", "running"] } },
- data: { state: "canceled" },
- });
- 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);
- });
- await del(objects.map((o) => o.r2Key));
+ await deleteProjectCascade(userId, id);
return Response.json({ ok: true });
} catch (e) {
return caught(e, "Could not delete project.");
diff --git a/site/src/cut/server/cloud/usage.ts b/site/src/cut/server/cloud/usage.ts
index e03a2279..ee9a60ab 100644
--- a/site/src/cut/server/cloud/usage.ts
+++ b/site/src/cut/server/cloud/usage.ts
@@ -1,5 +1,6 @@
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
+import { graceState } from "./grace";
import { cutLimitsFor } from "./limits";
export async function usageBytes(userId: string): Promise<number> {
@@ -37,6 +38,13 @@ export async function quotaCheck(userId: string, incoming: number): Promise<Resp
export const usageApi = {
async get(userId: string) {
const [bytes, limits] = await Promise.all([usageBytes(userId), cutLimitsFor(userId)]);
- return Response.json({ bytes, quotaBytes: limits.storageBytes });
+ const grace = await graceState(userId, bytes, limits);
+ return Response.json({
+ bytes,
+ quotaBytes: limits.storageBytes,
+ ...(grace && {
+ grace: { deadline: grace.deadline.toISOString(), overBytes: grace.overBytes },
+ }),
+ });
},
};