Skip to content

Open source CapCut alternative.

TypeScript

fix(site): cost ceilings on cloud jobs [rebuild]

David Lebd537851a75a
diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prisma
index a40102c8..6d2dd14a 100644
--- a/site/prisma/Cut.prisma
+++ b/site/prisma/Cut.prisma
@@ -189,7 +189,7 @@ model CutRenderJob {
userId String
projectId String?
kind String // export | preview | hls | import_url
- state String @default("queued") // queued | running | done | error | canceled
+ state String @default("queued") // queued | running | done | error | canceled | dismissed
progress Float @default(0)
spec Json
outputKey String?
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 906ab4c9..aa441529 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -1091,6 +1091,7 @@ async function postExport(
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
files: payload.pngs.map((p) => ({ name: p.name, bytes: p.blob.size })),
+ target: (payload.spec as { target?: string }).target ?? "export",
}),
});
const preBody =
diff --git a/site/src/cut/server/cloud/jobs.ts b/site/src/cut/server/cloud/jobs.ts
index 263390be..3ffd9d07 100644
--- a/site/src/cut/server/cloud/jobs.ts
+++ b/site/src/cut/server/cloud/jobs.ts
@@ -3,12 +3,12 @@
// shapes byte-match the engine's export routes (http/export.ts + server/jobs.ts).
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
-import { EXPORT_QUOTA_MARGIN, renderJobCheck } from "./limits";
+import { cutLimitsFor, EXPORT_QUOTA_MARGIN, renderJobCheck } from "./limits";
import { wakeRenderWorker } from "./wake";
import { getProject } from "./projects";
import { MEDIA_REDIRECT_HEADERS, mediaObjectUrl } from "./mediaCdn";
-import { head, overlayKey, presignPut, projectExportKey } from "./r2";
-import { addUsage, quotaCheck } from "./usage";
+import { del, head, overlayKey, presignPut, projectExportKey } from "./r2";
+import { addUsage, quotaCheck, reservedBytes, usageBytes } from "./usage";
import { caught, err, redirect } from "./util";
/** How long finished jobs stay in the export-jobs feed — the engine's registry
@@ -20,6 +20,28 @@ const FEED_WINDOW_MS = 24 * 60 * 60 * 1000;
* take on, because the wall-clock cost of a render depends on the machine. */
const CLIENT_RENDER_WINDOW_MS = 2 * 60 * 60 * 1000;
+// The spec goes straight to ffmpeg, so these are the largest frame, rate, and
+// length a render may ask for: a 4K cut at 60 fps, four hours long, is already
+// far past anything the editor produces.
+const MAX_RENDER_EDGE = 4096;
+const MAX_RENDER_FPS = 60;
+const MAX_RENDER_SECONDS = 4 * 60 * 60;
+const MAX_RENDER_CLIPS = 2000;
+
+// Overlay uploads are transient render inputs the quota never sees, so their
+// size is bounded here instead: per file, per batch, and by count. A render
+// carries one PNG per caption cue and one per frame of every animated
+// element, so the count and the batch run to a long, busy cut.
+const MAX_OVERLAY_FILES = 20_000;
+const MAX_OVERLAY_BYTES = 256 * 1024 ** 2;
+const MAX_OVERLAY_BATCH_BYTES = 8 * 1024 ** 3;
+
+// The largest download an import may land, holding for unlimited tiers too.
+const IMPORT_MAX_BYTES = 2 * 1024 ** 3;
+
+// A running job writes its row every second. One this quiet lost its worker.
+const HEARTBEAT_QUIET_MS = 30_000;
+
type JobRow = {
id: string;
projectId: string | null;
@@ -32,8 +54,57 @@ type JobRow = {
error: string | null;
claimedAt: Date | null;
createdAt: Date;
+ updatedAt: Date;
};
+/** Why a client-supplied render spec cannot run, or null when it can. */
+function specRefusal(spec: Record<string, unknown>): string | null {
+ const n = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : NaN);
+ const inRange = (v: unknown, lo: number, hi: number) => n(v) >= lo && n(v) <= hi;
+ if (!inRange(spec.width, 2, MAX_RENDER_EDGE) || !inRange(spec.height, 2, MAX_RENDER_EDGE))
+ return "Render size is out of range.";
+ if (!inRange(spec.fps, 1, MAX_RENDER_FPS)) return "Frame rate is out of range.";
+ if (!(n(spec.duration) > 0) || n(spec.duration) > MAX_RENDER_SECONDS)
+ return "Render length is out of range.";
+ if (Array.isArray(spec.clips) && spec.clips.length > MAX_RENDER_CLIPS) return "Too many clips.";
+ return null;
+}
+
+/** Whether a job's row needs the container started: it is waiting to be
+ * claimed, or it is marked running and its heartbeat has gone quiet — a worker
+ * that died mid-job, which the woken replacement sweeps back to queued. A
+ * healthy running job needs nothing, and a browser render (running with no
+ * claim) is never a worker's. */
+function needsWorker(row: JobRow): boolean {
+ if (row.state === "queued") return true;
+ return (
+ row.state === "running" &&
+ row.claimedAt !== null &&
+ Date.now() - row.updatedAt.getTime() > HEARTBEAT_QUIET_MS
+ );
+}
+
+/** The most bytes an import may bring in: what is left of the account's
+ * storage, under the hard ceiling. */
+async function importByteCeiling(userId: string): Promise<number> {
+ const limits = await cutLimitsFor(userId);
+ if (limits.storageBytes === null) return IMPORT_MAX_BYTES;
+ const [stored, reserved] = await Promise.all([usageBytes(userId), reservedBytes(userId)]);
+ return Math.max(0, Math.min(IMPORT_MAX_BYTES, limits.storageBytes - stored - reserved));
+}
+
+/** Drop the file a browser render uploaded for a row that never registered
+ * it: the bytes have no media row, so nothing else would ever find them. */
+async function dropUnregisteredExport(userId: string, row: JobRow): Promise<void> {
+ if (!row.projectId || !row.outName) return;
+ const key = projectExportKey(userId, row.projectId, row.outName);
+ const registered = await prisma.cutMediaObject.findUnique({
+ where: { r2Key: key },
+ select: { id: true },
+ });
+ if (!registered) await del([key]);
+}
+
/** Engine job status ("queued" | "running" | "done" | "error") from a row's
* state; a canceled row reads as the engine's canceled-export error. */
function engineStatus(row: JobRow): { status: string; error?: string } {
@@ -61,8 +132,11 @@ async function exportName(
where: { userId, projectId, kind: "export" },
select: { fileName: true },
}),
+ // A dismissed row stays for the day's count, and nothing sits behind its
+ // name: a released browser render never uploaded, a dismissed finished one
+ // is already in `files`.
tx.cutRenderJob.findMany({
- where: { userId, projectId, kind: "export" },
+ where: { userId, projectId, kind: "export", state: { not: "dismissed" } },
select: { outName: true },
}),
]);
@@ -86,8 +160,28 @@ export const jobsCloud = {
* Anything else is a 403 at R2. */
async exportPresign(userId: string, req: Request) {
try {
- const { files } = (await req.json()) as { files?: { name?: string; bytes?: number }[] };
+ const { files, target } = (await req.json()) as {
+ files?: { name?: string; bytes?: number }[];
+ target?: string;
+ };
if (!Array.isArray(files) || files.length === 0) return err("files is required.", 400);
+ if (files.length > MAX_OVERLAY_FILES) return err("Too many overlays.", 400);
+ // The overlays exist for a render, so the gates that render passes apply
+ // here too: a user's export meets the daily and live caps, the editor's
+ // own renders (proxy, card, ladder) only the storage margin.
+ if (target === undefined || target === "export") {
+ const capped = await renderJobCheck(userId);
+ if (capped) return capped;
+ }
+ const over = await quotaCheck(userId, 0, EXPORT_QUOTA_MARGIN);
+ if (over) return over;
+ let total = 0;
+ for (const f of files) {
+ if (!Number.isInteger(f.bytes) || f.bytes! < 1 || f.bytes! > MAX_OVERLAY_BYTES)
+ return err("Every overlay needs its size.", 400);
+ total += f.bytes!;
+ }
+ if (total > MAX_OVERLAY_BATCH_BYTES) return err("Overlays are too large.", 413);
const batchId = crypto.randomUUID().slice(0, 12);
const out = await Promise.all(
files.map(async (f) => {
@@ -95,7 +189,8 @@ export const jobsCloud = {
if (!name) throw new Error("Every overlay needs a name.");
const key = overlayKey(userId, batchId, name);
const type = name.toLowerCase().endsWith(".mp4") ? "video/mp4" : "image/png";
- return { name, key, type, url: await presignPut(key, type) };
+ // The size is in the signature: a larger body is a 403 at the bucket.
+ return { name, key, type, url: await presignPut(key, type, f.bytes) };
})
);
return Response.json({ files: out });
@@ -138,42 +233,47 @@ export const jobsCloud = {
body.spec.target === "hls"
? body.spec.target
: "export";
+ const refused = specRefusal(body.spec as Record<string, unknown>);
+ if (refused) return err(refused, 400);
+ // Every render lands bytes, so every target passes the storage margin.
+ // The finished file's size isn't knowable until it renders; what is
+ // knowable is whether this account is already too far past its quota to
+ // be handed more, so that is the gate. The daily and live caps count
+ // renders the user asked for; the editor's own renders are held to one
+ // running and one queued per project below.
if (target === "export") {
const capped = await renderJobCheck(userId);
if (capped) return capped;
- // The finished file is registered like any other object, so an export
- // grows storage. The output's size isn't knowable until it renders;
- // what is knowable is whether this account is already too far past its
- // quota to be handed more, so that is the gate. Previews and share
- // cards are the editor's own small internal renders and skip it.
- const over = await quotaCheck(userId, 0, EXPORT_QUOTA_MARGIN);
- if (over) return over;
}
+ const over = await quotaCheck(userId, 0, EXPORT_QUOTA_MARGIN);
+ if (over) return over;
const jobSpec = {
spec: body.spec,
overlays: body.overlays ?? [],
...(target === "hls" ? { burnedSubtitles: body.burnedSubtitles === true } : {}),
} as unknown as Prisma.InputJsonValue;
- if (target === "hls") {
- // A ladder is only worth rendering for a project someone can actually
- // open: it is fired by the editor rather than asked for, so without
- // this an unshared project would burn a render slot on a stream with no
- // viewer.
- const shared = await prisma.cutProjectShare.findUnique({
- where: { projectId },
- select: { id: true },
- });
- if (!shared) return Response.json({ id: null, skipped: "not-shared" });
+ if (target !== "export") {
+ if (target === "hls") {
+ // A ladder is only worth rendering for a project someone can actually
+ // open: it is fired by the editor rather than asked for, so without
+ // this an unshared project would burn a render slot on a stream with no
+ // viewer.
+ const shared = await prisma.cutProjectShare.findUnique({
+ where: { projectId },
+ select: { id: true },
+ });
+ if (!shared) return Response.json({ id: null, skipped: "not-shared" });
+ }
- // A ladder re-encodes the whole cut once per rung and holds a render
- // slot for the duration, so at most one runs and one waits. The waiting
- // one is REPLACED rather than kept: what matters is that the newest doc
- // renders last, and returning the in-flight job's id instead — as this
- // once did — silently dropped every edit made while one was running,
- // leaving the share streaming a pre-edit cut indefinitely.
+ // The editor's own renders re-encode the cut and hold a render slot
+ // for the duration, so per project at most one runs and one waits. The
+ // waiting one is REPLACED rather than kept: what matters is that the
+ // newest doc renders last, and returning the in-flight job's id instead
+ // — as this once did — silently dropped every edit made while one was
+ // running, leaving the share streaming a pre-edit cut indefinitely.
const queued = await prisma.cutRenderJob.findFirst({
- where: { userId, projectId, kind: "hls", state: "queued" },
+ where: { userId, projectId, kind: target, state: "queued" },
orderBy: { createdAt: "desc" },
select: { id: true },
});
@@ -245,9 +345,7 @@ export const jobsCloud = {
async exportStatus(userId: string, jobId: string) {
const row = await findJob(userId, jobId);
if (!row) return err("Unknown export.", 404);
- // "running" wakes too: if the worker died mid-job, the woken replacement
- // sweeps the stale row back to queued and picks it up.
- if (row.state === "queued" || row.state === "running") wakeRenderWorker();
+ if (needsWorker(row)) wakeRenderWorker();
const { status, error } = engineStatus(row);
return Response.json({
status,
@@ -263,11 +361,13 @@ export const jobsCloud = {
where: { id: jobId, userId, state: { in: ["queued", "running"] } },
data: { state: "canceled" },
});
- // A settled row is being dismissed from the dock: drop it from the feed
- // for good. A finished file survives as the project's export media object.
+ // A settled row is being dismissed from the dock: it leaves the feed and
+ // stays on the books, so the day's render count still sees it. A finished
+ // file survives as the project's export media object.
if (canceled.count === 0) {
- await prisma.cutRenderJob.deleteMany({
+ await prisma.cutRenderJob.updateMany({
where: { id: jobId, userId, state: { in: ["done", "error", "canceled"] } },
+ data: { state: "dismissed" },
});
}
return Response.json({ ok: true });
@@ -382,15 +482,22 @@ export const jobsCloud = {
/**
* Give back a name a browser render claimed but will not use.
*
- * The row is deleted rather than marked canceled: nothing rendered, so there
+ * The row is dismissed rather than marked canceled: nothing rendered, so there
* is nothing to report, and a canceled row would put a failure card in the
- * dock for a render the user themselves stopped.
+ * dock for a render the user themselves stopped. It stays on the books for
+ * the day's count, and anything the tab already uploaded under the claimed
+ * name goes with it.
*/
async exportClientRelease(userId: string, jobId: string) {
try {
- await prisma.cutRenderJob.deleteMany({
- where: { id: jobId, userId, kind: "export", state: { in: ["running", "queued"] } },
- });
+ const row = await findJob(userId, jobId);
+ if (row && row.kind === "export" && (row.state === "running" || row.state === "queued")) {
+ await dropUnregisteredExport(userId, row);
+ await prisma.cutRenderJob.updateMany({
+ where: { id: row.id, state: { in: ["running", "queued"] } },
+ data: { state: "dismissed" },
+ });
+ }
return Response.json({ ok: true });
} catch (e) {
return caught(e, "Could not release the export.");
@@ -420,22 +527,28 @@ export const jobsCloud = {
// claims those rows, so nothing else would ever release them, and each one
// left behind holds a name and a render slot for good. Any that have been
// running longer than a render plausibly takes are swept here, on the poll
- // that would have displayed them.
- await prisma.cutRenderJob
- .deleteMany({
- where: {
- userId,
- kind: "export",
- state: "running",
- claimedAt: null,
- updatedAt: { lt: new Date(Date.now() - CLIENT_RENDER_WINDOW_MS) },
- },
- })
- .catch(() => {});
+ // that would have displayed them: the row is dismissed (kept for the day's
+ // count) and a file the tab uploaded without registering goes.
+ const stale = await prisma.cutRenderJob.findMany({
+ where: {
+ userId,
+ kind: "export",
+ state: "running",
+ claimedAt: null,
+ updatedAt: { lt: new Date(Date.now() - CLIENT_RENDER_WINDOW_MS) },
+ },
+ });
+ for (const row of stale) {
+ await dropUnregisteredExport(userId, row).catch(() => {});
+ await prisma.cutRenderJob
+ .updateMany({ where: { id: row.id, state: "running" }, data: { state: "dismissed" } })
+ .catch(() => {});
+ }
const rows = await prisma.cutRenderJob.findMany({
where: {
userId,
kind: "export",
+ state: { not: "dismissed" },
OR: [
{ state: { in: ["queued", "running"] } },
{ createdAt: { gte: new Date(Date.now() - FEED_WINDOW_MS) } },
@@ -476,12 +589,21 @@ export const jobsCloud = {
if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
const capped = await renderJobCheck(userId);
if (capped) return capped;
+ // What lands counts against storage, so an account with none left gets
+ // no download, and the worker downloads no more than what is left.
+ const over = await quotaCheck(userId, 0);
+ if (over) return over;
+ const maxBytes = await importByteCeiling(userId);
const row = await prisma.cutRenderJob.create({
data: {
userId,
projectId,
kind: "import_url",
- spec: { url, ...(audio === true ? { audio: true } : {}) } as unknown as Prisma.InputJsonValue,
+ spec: {
+ url,
+ maxBytes,
+ ...(audio === true ? { audio: true } : {}),
+ } as unknown as Prisma.InputJsonValue,
},
});
wakeRenderWorker();
@@ -504,12 +626,16 @@ export const jobsCloud = {
if (!url) return err("No URL provided.", 400);
const capped = await renderJobCheck(userId);
if (capped) return capped;
+ const over = await quotaCheck(userId, 0);
+ if (over) return over;
+ const maxBytes = await importByteCeiling(userId);
const row = await prisma.cutRenderJob.create({
data: {
userId,
kind: "import_url",
spec: {
url,
+ maxBytes,
target: "library",
...(audio === true ? { audio: true } : {}),
// An inspiration link's downloads land in the Inspiration folder,
@@ -532,6 +658,8 @@ export const jobsCloud = {
const { file, maxHeight } = (await req.json()) as { file?: string; maxHeight?: number };
if (!file) return err("file is required.", 400);
if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
+ const over = await quotaCheck(userId, 0, EXPORT_QUOTA_MARGIN);
+ if (over) return over;
const source = await prisma.cutMediaObject.findFirst({
where: { userId, projectId, fileName: file, kind: "media" },
select: { id: true },
@@ -558,7 +686,7 @@ export const jobsCloud = {
async status(userId: string, jobId: string) {
const row = await findJob(userId, jobId);
if (!row) return err("Unknown job.", 404);
- if (row.state === "queued" || row.state === "running") wakeRenderWorker();
+ if (needsWorker(row)) wakeRenderWorker();
return Response.json({
id: row.id,
kind: row.kind,
diff --git a/site/src/cut/server/cloud/limits.ts b/site/src/cut/server/cloud/limits.ts
index 12841e7d..be1b0d3e 100644
--- a/site/src/cut/server/cloud/limits.ts
+++ b/site/src/cut/server/cloud/limits.ts
@@ -8,8 +8,20 @@ import { prisma } from "@/lib/prisma";
export type CutLimits = {
storageBytes: number | null;
renderJobsPerDay: number | null;
+ /** Renders the user asked for that may be queued or running at once: the
+ * worker pool is shared, so one account queueing by the dozen would hold
+ * every other account's export behind it. */
+ liveJobs: number | null;
+ /** Chat turns in flight across the account's projects. */
+ liveTurns: number | null;
+ /** Clip titles a day — they are on the house. */
+ titlesPerDay: number | null;
};
+/** The kinds the daily cap counts: renders the user asked for. Hover proxies,
+ * share cards, ladders and chat turns are bounded by the live cap instead. */
+export const COUNTED_JOB_KINDS = ["export", "import_url", "convert"];
+
export const FREE_STORAGE_BYTES = 250 * 1024 ** 2;
/** Headroom an export may render into past the storage quota. A finished
@@ -20,9 +32,27 @@ export const FREE_STORAGE_BYTES = 250 * 1024 ** 2;
* or for Pro. */
export const EXPORT_QUOTA_MARGIN = 1.2;
-const FREE: CutLimits = { storageBytes: FREE_STORAGE_BYTES, renderJobsPerDay: 10 };
-const PRO: CutLimits = { storageBytes: 100 * 1024 ** 3, renderJobsPerDay: 200 };
-const UNLIMITED: CutLimits = { storageBytes: null, renderJobsPerDay: null };
+const FREE: CutLimits = {
+ storageBytes: FREE_STORAGE_BYTES,
+ renderJobsPerDay: 10,
+ liveJobs: 8,
+ liveTurns: 4,
+ titlesPerDay: 300,
+};
+const PRO: CutLimits = {
+ storageBytes: 100 * 1024 ** 3,
+ renderJobsPerDay: 200,
+ liveJobs: 32,
+ liveTurns: 8,
+ titlesPerDay: 2000,
+};
+const UNLIMITED: CutLimits = {
+ storageBytes: null,
+ renderJobsPerDay: null,
+ liveJobs: null,
+ liveTurns: null,
+ titlesPerDay: null,
+};
/** The limits an account's tier earns. Super users are unlimited. */
export function cutLimitsForTier(tier: { superUser: boolean; pro: boolean }): CutLimits {
@@ -35,13 +65,43 @@ export async function cutLimitsFor(userId: string): Promise<CutLimits> {
return cutLimitsForTier({ superUser: false, pro: !!(await getActiveProSubscription(userId)) });
}
-/** 429 when another counted render job would break the daily cap, else null. */
+/** 429 when the account already has as many asked-for jobs in flight as its
+ * tier allows, else null. The editor's own renders (proxy, card, ladder) are
+ * held to one running and one queued per project instead, so background work
+ * the user cannot see never refuses the export they asked for. */
+export async function liveJobCheck(userId: string): Promise<Response | null> {
+ const limits = await cutLimitsFor(userId);
+ if (limits.liveJobs === null) return null;
+ const live = await prisma.cutRenderJob.count({
+ where: {
+ userId,
+ kind: { in: [...COUNTED_JOB_KINDS, "agent_turn"] },
+ state: { in: ["queued", "running"] },
+ },
+ });
+ if (live < limits.liveJobs) return null;
+ return Response.json(
+ {
+ error: "Too many jobs are running on this account. Wait for one to finish.",
+ code: "live_job_limit",
+ limit: limits.liveJobs,
+ },
+ { status: 429 }
+ );
+}
+
+/** 429 when another counted render job would break the daily cap or the live
+ * cap, else null. The daily count reads every row of the day whatever its
+ * state — a dismissed or canceled job was still a render this account asked
+ * for — so nothing the user does to the dock changes the count. */
export async function renderJobCheck(userId: string): Promise<Response | null> {
+ const live = await liveJobCheck(userId);
+ if (live) return live;
const limits = await cutLimitsFor(userId);
if (limits.renderJobsPerDay === null) return null;
const since = new Date(Date.now() - 24 * 60 * 60 * 1000);
const used = await prisma.cutRenderJob.count({
- where: { userId, kind: { in: ["export", "import_url", "convert"] }, createdAt: { gte: since } },
+ where: { userId, kind: { in: COUNTED_JOB_KINDS }, createdAt: { gte: since } },
});
if (used < limits.renderJobsPerDay) return null;
// `error` is what the client's shared error paths render — keep it human.
diff --git a/site/src/cut/server/cloud/turns.ts b/site/src/cut/server/cloud/turns.ts
index 8e680229..a8be17e4 100644
--- a/site/src/cut/server/cloud/turns.ts
+++ b/site/src/cut/server/cloud/turns.ts
@@ -5,6 +5,7 @@
// a time per project — and the generic /jobs/:jobId route serves the poll.
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
+import { cutLimitsFor, liveJobCheck } from "./limits";
import { getProject } from "./projects";
import { caught, err } from "./util";
import { wakeRenderWorker } from "./wake";
@@ -22,6 +23,18 @@ export const turnsCloud = {
async queue(userId: string, projectId: string, req: Request) {
try {
if (!(await getProject(userId, projectId))) return err("Project not found.", 404);
+ const capped = await liveJobCheck(userId);
+ if (capped) return capped;
+ // Turns run one per project; across projects an account holds its
+ // tier's count at once, so opening projects by the hundred earns a wait.
+ const { liveTurns: maxTurns } = await cutLimitsFor(userId);
+ if (maxTurns !== null) {
+ const liveTurns = await prisma.cutRenderJob.count({
+ where: { userId, kind: "agent_turn", state: { in: ["queued", "running"] } },
+ });
+ if (liveTurns >= maxTurns)
+ return err("Too many turns are running on this account. Wait for one to finish.", 429);
+ }
const text = await req.text();
if (text.length > MAX_TURN_BYTES) return err("Turn too large.", 413);
const body = JSON.parse(text) as Partial<AgentTurnSpec>;
diff --git a/site/src/cut/server/cloud/wake.ts b/site/src/cut/server/cloud/wake.ts
index 58ffe0e2..6740e991 100644
--- a/site/src/cut/server/cloud/wake.ts
+++ b/site/src/cut/server/cloud/wake.ts
@@ -8,6 +8,13 @@ import { CUT_WORKER_WAKE_URL } from "@/cut/lib/hosts";
const wakeSecret = () => process.env.CUT_RENDER_WAKE_SECRET;
+// A wake is idempotent on the Worker side, and the clients poll their jobs
+// several times a second, so one wake per window per process is all the
+// container ever needs. Without this, one status loop starts every replica
+// on every poll.
+const WAKE_WINDOW_MS = 5_000;
+let lastWakeAt = 0;
+
// A wake that never lands strands every render — the container is not started
// and jobs queue forever — and retrying can't help, because the address itself
// is wrong. Nothing waits on the result, so the log is the only place it can
@@ -15,6 +22,9 @@ const wakeSecret = () => process.env.CUT_RENDER_WAKE_SECRET;
export function wakeRenderWorker(): void {
const secret = wakeSecret();
if (!secret) return;
+ const now = Date.now();
+ if (now - lastWakeAt < WAKE_WINDOW_MS) return;
+ lastWakeAt = now;
void fetch(CUT_WORKER_WAKE_URL, {
method: "POST",
headers: { authorization: `Bearer ${secret}` },
diff --git a/site/src/cut/worker/importUrlJob.ts b/site/src/cut/worker/importUrlJob.ts
index 9d062b49..3e3a5e8b 100644
--- a/site/src/cut/worker/importUrlJob.ts
+++ b/site/src/cut/worker/importUrlJob.ts
@@ -1,4 +1,4 @@
-import { mkdtemp, rm } from "node:fs/promises";
+import { mkdtemp, rm, stat } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type { Prisma } from "@/generated/prisma/client";
@@ -35,12 +35,19 @@ export async function runImportUrlJob(
job: ClaimedJob,
isCanceled: () => boolean
): Promise<ImportUrlResult | LibraryImportResult> {
- const { url, target, origin, audio } = (job.spec ?? {}) as {
+ const { url, target, origin, audio, maxBytes } = (job.spec ?? {}) as {
url?: string;
target?: string;
origin?: string;
audio?: boolean;
+ /** What is left of the account's storage when the job was queued; the
+ * route always sets it. Everything that came down is measured against it
+ * before any byte is uploaded — the one place every rung and every
+ * conversion passes through. */
+ maxBytes?: number;
};
+ if (typeof maxBytes !== "number" || !(maxBytes > 0))
+ throw new Error("There is no storage left on this account for an import.");
if (!url || !/^https?:\/\//i.test(url.trim())) throw new Error("Enter a valid http(s) URL.");
const toLibrary = target === "library";
const projectId = job.projectId;
@@ -62,6 +69,13 @@ export async function runImportUrlJob(
try {
const dl = await download(url.trim(), tmp, { audio: audio === true });
if (isCanceled()) throw new Error("Import canceled.");
+ let landing = 0;
+ for (const f of dl.files) {
+ landing += (await stat(f.file)).size;
+ if (f.poster) landing += (await stat(f.poster)).size;
+ }
+ if (landing > maxBytes)
+ throw new Error("The download is larger than the storage left on this account.");
const rows = await prisma.cutMediaObject.findMany({
where: toLibrary ? { userId: job.userId, kind: "library" } : { projectId, kind: "media" },
diff --git a/site/src/cut/worker/main.ts b/site/src/cut/worker/main.ts
index 1d384ed1..3b2bf0cd 100644
--- a/site/src/cut/worker/main.ts
+++ b/site/src/cut/worker/main.ts
@@ -40,8 +40,24 @@ const SWEEP_EVERY_MS = 15_000;
// going when it closes.
const DRAIN_MS = 13 * 60_000;
+/** The longest a job of each kind may run. Everything else about a job's cost
+ * is bounded when it is queued; this bounds the one thing that isn't — a
+ * render that keeps ffmpeg talking forever holds a billed container. */
+const MAX_RUNTIME_MS: Record<string, number> = {
+ export: 60 * 60_000,
+ preview: 20 * 60_000,
+ card: 10 * 60_000,
+ hls: 3 * 60 * 60_000,
+ import_url: 20 * 60_000,
+ convert: 60 * 60_000,
+ agent_turn: 20 * 60_000,
+};
+const DEFAULT_MAX_RUNTIME_MS = 60 * 60_000;
+
interface ActiveJob {
handle: RenderHandle;
+ kind: string;
+ startedAt: number;
canceled: boolean;
/** This job goes back on the queue rather than settling here — swept out
* from under us after a heartbeat gap, or still rendering when a shutdown
@@ -110,6 +126,16 @@ function watchJob(id: string, entry: ActiveJob): ReturnType<typeof setInterval>
return setInterval(() => {
void (async () => {
try {
+ if (Date.now() - entry.startedAt > (MAX_RUNTIME_MS[entry.kind] ?? DEFAULT_MAX_RUNTIME_MS)) {
+ entry.canceled = true; // suppress the run's own row writes
+ entry.handle.error = "Ran too long.";
+ entry.handle.proc?.kill("SIGKILL");
+ await prisma.cutRenderJob.updateMany({
+ where: { id, state: "running" },
+ data: { state: "error", error: "The job ran too long and was stopped." },
+ });
+ return;
+ }
const row = await prisma.cutRenderJob.findUnique({
where: { id },
select: { state: true },
@@ -140,7 +166,13 @@ function watchJob(id: string, entry: ActiveJob): ReturnType<typeof setInterval>
async function runJob(job: ClaimedJob): Promise<void> {
const handle: RenderHandle = { tmpDir: "", outPath: "", progress: 0, log: [] };
- const entry: ActiveJob = { handle, canceled: false, retry: false };
+ const entry: ActiveJob = {
+ handle,
+ kind: job.kind,
+ startedAt: Date.now(),
+ canceled: false,
+ retry: false,
+ };
active.set(job.id, entry);
const watcher = watchJob(job.id, entry);
try {