Skip to content

Open source CapCut alternative.

TypeScript
49.4 KB
Raw Blame
// Render-job rows for the cloud worker (site/src/cut/worker). These routes only
// manage CutRenderJob rows — the worker claims and executes them. Response
// shapes byte-match the engine's export routes (http/export.ts + server/jobs.ts).
import type { Prisma } from "@/generated/prisma/client";
import { getGlobalSetting } from "@/lib/config/effective";
import { prisma } from "@/lib/prisma";
import { EXPORT_QUOTA_MARGIN, renderJobCheck } from "./limits";
import { wakeRenderWorker } from "./wake";
import { queuePreview } from "./previewJobs";
import { getProject } from "./projects";
import { MEDIA_REDIRECT_HEADERS, mediaObjectUrl, mediaUrlLifetime } from "./mediaCdn";
import { del, head, overlayKey, overlayPrefix, presignPut, projectExportKey } from "./r2";
import { contentTypeFor } from "../serveFile";
import { containerOfName, deliveryContainer, exportBaseName, jobWantsStems, specMediaFiles, STEMS_MIME, stemsArchiveName, type ExportContainer, type ExportFiles } from "../../lib/exportDelivery";
import { convertModeIn } from "../../lib/convertMode";
import { LOUDNESS_IDS, type LoudnessId } from "../../lib/loudnessSettings";
import type { DocExportAudio } from "../../lib/exportPresets";
import { compatCoverIn, compatCovers, isLightProxyName, PROXY_SOURCE_FAULT, type CompatCover } from "../../lib/proxyNames";
import { addUsage, outputByteCeiling, quotaCheck } from "./usage";
import { caught, err, redirect } from "./util";
import { errorFields, failureCode, UserError, type ErrorFields } from "@/cut/lib/userError";

const HOUR_MS = 60 * 60 * 1000;

/** A master's file name without its extension: what its proxy's name starts
 * with (server/proxy.ts `proxyNameFor`). */
const proxyStem = (fileName: string) => fileName.replace(/\.[^./\\]+$/, "") || "media";

/** The newest proxy of `file` already built that answers an ask: light or
 * full quality, and the compat cover it names (lib/proxyNames.ts). */
async function builtProxy(userId: string, projectId: string, file: string, light: boolean, compat: CompatCover | null) {
  // A compat proxy is named from the whole master name, as a light one is.
  let prefix = light ? `${file}.light` : `${proxyStem(file)}.proxy`;
  if (compat) {
    prefix = light ? `${file}.compat.light` : `${file}.compat`;
  }
  const rows = await prisma.cutMediaObject.findMany({
    where: { userId, projectId, kind: "proxy", uploadState: "complete", fileName: { startsWith: prefix } },
    select: { fileName: true, bytes: true },
    orderBy: { createdAt: "desc" },
  });
  if (!compat) {
    return rows[0] ?? null;
  }

  // `clip.mp4.compat` also starts `clip.mp4.compat.light`: a full-size ask
  // takes a full-size proxy that covers the stream.
  return rows.find((r) => compatCovers(r.fileName, compat) && isLightProxyName(r.fileName) === light) ?? null;
}

/** Whether a proxy job's spec asked for what this request asks. */
function sameProxyAsk(spec: unknown, light: boolean, compat: CompatCover | null): boolean {
  const s = (spec ?? {}) as { maxHeight?: number; compat?: unknown };
  return (s.maxHeight !== undefined) === light && compatCoverIn(s.compat) === compat;
}

/** How long finished jobs stay in the export-jobs feed — the engine's registry
 * keeps a bounded terminal backlog; the cloud keeps a day. */
const FEED_WINDOW_MS = 24 * 60 * 60 * 1000;

/** How long a browser render may hold its reserved name before it is treated
 * as a tab that went away. Generous next to the ten-minute cut the client will
 * 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;
// A render's inputs: overlay stills, and for a browser-resident project the
// cut's own media, which rides with the job because the worker has no other
// way to reach a file that lives in a tab. A source clip can be as large as
// any upload.
const MAX_OVERLAY_BYTES = 4 * 1024 ** 3;
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 = {
  spec: unknown;
  id: string;
  projectId: string | null;
  kind: string;
  state: string;
  progress: number;
  outputKey: string | null;
  outName: string | null;
  result: unknown;
  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>): UserError | 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 new UserError("render_size_out_of_range", "Render size is out of range.");
  if (!inRange(spec.fps, 1, MAX_RENDER_FPS)) return new UserError("render_fps_out_of_range", "Frame rate is out of range.");
  if (!(n(spec.duration) > 0) || n(spec.duration) > MAX_RENDER_SECONDS)
    return new UserError("render_length_out_of_range", "Render length is out of range.");
  if (Array.isArray(spec.clips) && spec.clips.length > MAX_RENDER_CLIPS) return new UserError("render_too_many_clips", "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. */
export function needsWorker(row: Pick<JobRow, "state" | "claimedAt" | "updatedAt">): boolean {
  if (row.state === "queued") return true;
  return (
    row.state === "running" &&
    row.claimedAt !== null &&
    Date.now() - row.updatedAt.getTime() > HEARTBEAT_QUIET_MS
  );
}

/** A client's own id for an import — the phone's inspiration item, the
 * page's pending card. One path segment's worth of characters. */
const validImportKey = (key: unknown): key is string | undefined =>
  key === undefined || (typeof key === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(key));

/** The import the client already queued under this key. A phone that never
 * heard the first answer, or a page retrying its card, posts the same link
 * again with the key it made for the item and gets the job it already has —
 * the link lands once. A job that failed or was canceled is not handed back:
 * a repeat after one of those is the retry the client means. */
async function importJobFor(userId: string, key: string | undefined): Promise<{ id: string } | null> {
  if (!key) return null;
  return prisma.cutRenderJob.findFirst({
    where: {
      userId,
      kind: "import_url",
      state: { in: ["queued", "running", "done"] },
      spec: { path: ["key"], equals: key },
    },
    select: { id: true },
  });
}

/** 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 left = await outputByteCeiling(userId);
  return left === null ? IMPORT_MAX_BYTES : Math.min(IMPORT_MAX_BYTES, left);
}

/** The most bytes an export's output may land, for the worker to hold its own
 * render to. A render that outgrows it is refused before it is uploaded, so an
 * account cannot pass the gate small and land large. */
async function exportByteCeiling(userId: string): Promise<number | null> {
  return outputByteCeiling(userId, EXPORT_QUOTA_MARGIN);
}

/** 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: Pick<JobRow, "projectId" | "outName" | "spec">
): Promise<void> {
  if (!row.projectId || !row.outName) return;

  // Stems land before the file and go with it, for a render that asked for
  // them. A plain export's stems name can belong to another export's zip,
  // registered or still landing, and that zip stays.
  const names = jobWantsStems(row.spec) ? [row.outName, stemsArchiveName(row.outName)] : [row.outName];
  const keys = names.map((name) => projectExportKey(userId, row.projectId!, name));
  const registered = await prisma.cutMediaObject.findMany({
    where: { r2Key: { in: keys } },
    select: { r2Key: true },
  });
  const kept = new Set(registered.map((r) => r.r2Key));
  await del(keys.filter((k) => !kept.has(k)));
}

const EXPORT_CANCELED = new UserError("export_canceled", "Export canceled.");

type RowFailure = Pick<ErrorFields, "errorCode" | "errorParams">;

/** The code the worker recorded beside a failed row's error (worker/main.ts
 * keeps it in `result`), so the page words the failure in its language. */
function rowFailure(result: unknown): RowFailure {
  const coded = failureCode(result);
  return coded ? { errorCode: coded.code, errorParams: coded.params } : {};
}

/** The recorded failure of each failed row among `rows`, read in one query:
 * only a failed row's result is fetched, and only once it has failed. */
async function rowFailures(rows: Pick<JobRow, "id" | "state">[]): Promise<Map<string, RowFailure>> {
  const failed = rows.filter((r) => r.state === "error").map((r) => r.id);
  if (failed.length === 0) return new Map();
  const found = await prisma.cutRenderJob.findMany({ where: { id: { in: failed } }, select: { id: true, result: true } });
  return new Map(found.map((r) => [r.id, rowFailure(r.result)]));
}

/** 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: Pick<JobRow, "state" | "error">,
  failure: RowFailure = {}
): { status: string; error?: string } & RowFailure {
  if (row.state === "canceled") {
    return row.error ? { status: "error", error: row.error } : { status: "error", ...errorFields(EXPORT_CANCELED, "") };
  }
  return { status: row.state, error: row.error ?? undefined, ...(row.error ? failure : {}) };
}

/** Everything the job routes read except the two big JSON columns. The spec
 * holds the whole document a render was cut from and the result is the payload
 * of a finished job; a status poll runs every couple of seconds and wants
 * neither, so they are fetched on their own once a job has settled. */
const jobRowSelect = {
  id: true,
  projectId: true,
  kind: true,
  state: true,
  progress: true,
  outputKey: true,
  outName: true,
  error: true,
  claimedAt: true,
  createdAt: true,
  updatedAt: true,
} as const;

type LeanJobRow = Omit<JobRow, "result" | "spec">;

async function findJob(userId: string, id: string): Promise<LeanJobRow | null> {
  return prisma.cutRenderJob.findFirst({ where: { id, userId }, select: jobRowSelect });
}

/** Engine-style export name: the base with the container's extension and a
 * " 2", " 3"… suffix when taken
 * by an existing export object or a job still in flight. The client derives the
 * base from the project name; the dedupe happens here, where the rows are. An
 * export with stems needs its stems' name free too, and every job in flight
 * holds its stems' name. */
async function exportName(
  userId: string,
  projectId: string,
  baseName: string,
  container: ExportContainer | undefined,
  tx: Prisma.TransactionClient | typeof prisma,
  claim: ExportFiles
) {
  // The spec's container names the extension, the same way the engine's
  // `containerExtension` does; a name alone (a tab's own claim) says it by its
  // suffix.
  const { ext } = container ? deliveryContainer(container) : containerOfName(baseName);
  const base = exportBaseName(baseName);
  const [files, jobs] = await Promise.all([
    tx.cutMediaObject.findMany({
      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", state: { not: "dismissed" } },
      select: { outName: true },
    }),
  ]);
  const taken = new Set<string>([
    ...files.map((f) => f.fileName),
    ...jobs.flatMap((j) => (j.outName ? [j.outName, stemsArchiveName(j.outName)] : [])),
  ]);
  for (let n = 1; ; n++) {
    const candidate = n === 1 ? `${base}${ext}` : `${base} ${n}${ext}`;
    if (!taken.has(candidate) && !(claim === "fileAndStems" && taken.has(stemsArchiveName(candidate)))) return candidate;
  }
}

/** Queue a render of the stored document at a named size. A refusal — a
 * missing project, the render or storage caps — comes back as its Response. */
export async function queueDocExport(
  userId: string,
  projectId: string,
  preset: string,
  audio: DocExportAudio = {}
): Promise<{ id: string; outName: string } | Response> {
  const project = await getProject(userId, projectId);
  if (!project) return err(new UserError("project_not_found", "Project not found."), 404);
  const capped = await renderJobCheck(userId);
  if (capped) return capped;
  const over = await quotaCheck(userId, 0, EXPORT_QUOTA_MARGIN);
  if (over) return over;
  // What the render may land. The worker holds its own output to it, so a
  // queued export cannot pass this gate and then write past the account's cap.
  const maxBytes = await exportByteCeiling(userId);
  const outName = await exportName(userId, projectId, project.name, undefined, prisma, audio.stems ? "fileAndStems" : "file");
  const row = await prisma.cutRenderJob.create({
    data: {
      userId,
      projectId,
      kind: "export",
      spec: {
        fromDoc: {
          preset,
          ...(audio.loudness ? { loudness: audio.loudness } : {}),
          ...(audio.stems ? { stems: true } : {}),
          snapshot: { doc: project.doc, version: String(project.version) },
        },
        ...(maxBytes === null ? {} : { maxBytes }),
      } as unknown as Prisma.InputJsonValue,
      outName,
    },
  });
  wakeRenderWorker();
  return { id: row.id, outName };
}

/** Queue a URL import into a project. `adopt` asks the worker to register
 * what lands as project assets itself — for a caller with no editor of its
 * own to adopt them (the ChatGPT app); `name` is what that asset is called.
 * A refusal comes back as its Response. */
export async function queueImportUrl(
  userId: string,
  projectId: string,
  opts: { url: string; audio?: boolean; key?: string; name?: string }
): Promise<{ id: string } | Response> {
  if (!(await getProject(userId, projectId))) return err(new UserError("project_not_found", "Project not found."), 404);
  const open = await importJobFor(userId, opts.key);
  if (open) return { id: open.id };
  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: opts.url,
        maxBytes,
        ...(opts.audio === true ? { audio: true } : {}),
        ...(opts.key ? { key: opts.key } : {}),
        // The name the caller gave the file, for whoever adopts it.
        ...(opts.name ? { name: opts.name } : {}),
      } as unknown as Prisma.InputJsonValue,
    },
  });
  wakeRenderWorker();
  return { id: row.id };
}

export const jobsCloud = {
  /** Presign the overlay uploads for an export — stamped title and effect
   * frames, and the behind-speaker mask clip. Transient worker inputs: no
   * CutMediaObject bookkeeping, no quota.
   *
   * The content type is part of a presigned PUT's signature, so the answer
   * carries the one that was signed and the uploader sends it back verbatim.
   * Anything else is a 403 at R2. */
  async exportPresign(userId: string, req: Request) {
    try {
      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(new UserError("render_too_many_overlays", "Too many overlays."), 400);
      // Retained exports pass their storage and render gates before staging inputs.
      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) return err("Every overlay needs its size.", 400);
        if (f.bytes! > MAX_OVERLAY_BYTES) return err(`${f.name} is too large to render in the cloud.`, 413);
        total += f.bytes!;
      }
      if (total > MAX_OVERLAY_BATCH_BYTES) return err(new UserError("render_files_too_large", "The cut's files are too large to render in the cloud."), 413);
      const batchId = crypto.randomUUID().slice(0, 12);
      const out = await Promise.all(
        files.map(async (f) => {
          const name = String(f.name ?? "").replace(/[/\\]/g, "");
          if (!name) throw new Error("Every overlay needs a name.");
          const key = overlayKey(userId, batchId, name);
          const type = contentTypeFor(name);
          // 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 });
    } catch (e) {
      return caught(e, new UserError("render_overlays_presign_failed", "Could not presign the overlays."));
    }
  },

  /** Queue an export (or hover-preview) render. Same response as the engine's
   * exportApi.create: {id} or 400 {error}. */
  async exportCreate(userId: string, req: Request) {
    try {
      const body = (await req.json()) as {
        spec?: {
          target?: string;
          projectId?: string;
          container?: ExportContainer;
          clips?: { file?: string }[];
          overlayVideos?: { file?: string }[];
          audio?: { file?: string }[];
          stemPlan?: unknown[];
        };
        overlays?: { name: string; key: string }[];
        projectId?: string;
        outName?: string;
        burnedSubtitles?: boolean;
        revision?: string;
        /** "overlays": the cut's media was uploaded beside the stills, so the
         * project it names is not one the cloud stores — a browser-resident
         * project borrowing the worker. */
        mediaFrom?: "overlays";
      };
      if (!body.spec || typeof body.spec !== "object") return err("spec is required.", 400);
      const projectId = body.projectId ?? body.spec.projectId;
      if (!projectId) return err("projectId is required.", 400);
      if (body.revision !== undefined && (typeof body.revision !== "string" || body.revision.length > 128 || !body.revision))
        return err("Invalid render revision.", 400);
      const borrowed = body.mediaFrom === "overlays";
      const project = await getProject(userId, projectId);
      if (!project && !borrowed) return err(new UserError("project_not_found", "Project not found."), 400);
      // Overlay keys come from the client; only this user's own overlay
      // uploads are acceptable render inputs — anything else would let a
      // crafted key pull another account's R2 objects into the render.
      const overlayPrefix = `cut/${userId}/overlays/`;
      for (const o of body.overlays ?? []) {
        if (typeof o?.key !== "string" || !o.key.startsWith(overlayPrefix)) {
          return err("Invalid overlay key.", 400);
        }
      }
      if (borrowed) {
        // Every file the cut plays has to have come up with the job; the
        // worker has nowhere else to look for it.
        const uploaded = new Set((body.overlays ?? []).map((o) => o.name));
        const missing = specMediaFiles(body.spec).find((f) => !uploaded.has(f));
        if (missing) return err(`${missing} was not uploaded with the export.`, 400);
        if (!body.outName?.trim()) return err("outName is required.", 400);
      }
      // Hover proxies, share cards and share ladders are renders the editor
      // fires on its own; only renders the user asked for count against the
      // cap.
      const target =
        body.spec.target === "preview" ||
        body.spec.target === "card" ||
        body.spec.target === "hls"
          ? body.spec.target
          : "export";
      const refused = specRefusal(body.spec as Record<string, unknown>);
      if (refused) return err(refused, 400);
      // Retained exports pass storage and render gates. Derived playback
      // artifacts use a bounded queue and expire through garbage collection.
      let maxBytes: number | null = null;
      if (target === "export") {
        const capped = await renderJobCheck(userId);
        if (capped) return capped;
        const over = await quotaCheck(userId, 0, EXPORT_QUOTA_MARGIN);
        if (over) return over;
        maxBytes = await exportByteCeiling(userId);
      }
      const jobSpec = {
        ...(body.revision ? { revision: body.revision } : {}),
        spec: body.spec,
        overlays: body.overlays ?? [],
        ...(borrowed ? { mediaFrom: "overlays" } : {}),
        ...(target === "hls" ? { burnedSubtitles: body.burnedSubtitles === true } : {}),
        ...(maxBytes === null ? {} : { maxBytes }),
      } as unknown as Prisma.InputJsonValue;

      if (target === "preview") {
        const row = await queuePreview(userId, projectId, jobSpec, body.revision);
        return Response.json({ id: row.id });
      }

      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" });
        }

        // 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: target, state: "queued" },
          orderBy: { createdAt: "desc" },
          select: { id: true },
        });
        if (queued) {
          const replaced = await prisma.cutRenderJob.updateMany({
            where: { id: queued.id, state: "queued" },
            data: { spec: jobSpec },
          });
          // It started between the read and the write, so it is now the running
          // job and this doc needs a fresh row behind it.
          if (replaced.count > 0) {
            wakeRenderWorker();
            return Response.json({ id: queued.id });
          }
        }
      }
      const outName =
        target === "export"
          ? await exportName(
              userId,
              projectId,
              body.outName?.trim() || project?.name || "export",
              body.spec.container,
              prisma,
              body.spec.stemPlan?.length ? "fileAndStems" : "file"
            )
          : target === "hls"
            ? "master.m3u8"
            : `${target}.mp4`;
      const row = await prisma.cutRenderJob.create({
        data: { userId, projectId, kind: target, spec: jobSpec, outName },
      });
      wakeRenderWorker();
      return Response.json({ id: row.id });
    } catch (e) {
      return caught(e, new UserError("export_start_failed", "Export failed to start."));
    }
  },

  /** Capture the requested document in the queue; the worker prepares its render spec. */
  async exportFromDoc(userId: string, projectId: string, req: Request) {
    try {
      const body = (await req.json().catch(() => ({}))) as { preset?: string; loudness?: unknown; stems?: unknown };
      if (body.loudness !== undefined && !LOUDNESS_IDS.includes(body.loudness as LoudnessId))
        return err(`loudness must be one of ${LOUDNESS_IDS.join(", ")}.`, 400);
      // The worker owns the size list (it builds the spec), and falls back to
      // the source-matched original for anything it does not know.
      const queued = await queueDocExport(userId, projectId, typeof body.preset === "string" ? body.preset : "original", {
        loudness: body.loudness as LoudnessId | undefined,
        stems: body.stems === true,
      });
      if (queued instanceof Response) return queued;
      return Response.json(queued);
    } catch (e) {
      return caught(e, new UserError("export_start_failed", "Export failed to start."));
    }
  },

  async exportStatus(userId: string, jobId: string) {
    const row = await findJob(userId, jobId);
    if (!row) return err(new UserError("export_unknown", "Unknown export."), 404);
    if (needsWorker(row)) wakeRenderWorker();
    const { status, error, ...failure } = engineStatus(row, (await rowFailures([row])).get(row.id));
    const finished = row.state === "done" && row.outputKey;
    // The artifact names the revision the render was cut from, which only the
    // spec knows. One read, on the poll that ends the wait.
    const spec = finished
      ? ((
          await prisma.cutRenderJob.findUnique({ where: { id: row.id }, select: { spec: true } })
        )?.spec as { revision?: string } | null)
      : null;
    return Response.json({
      status,
      progress: row.progress,
      error,
      ...failure,
      outName: row.outName || undefined,
      artifact: finished ? {
        id: row.id, projectId: row.projectId, kind: row.kind,
        url: mediaObjectUrl(row.outputKey!), expiresIn: mediaUrlLifetime(),
        revision: spec?.revision ?? null,
      } : null,
    });
  },

  async exportCancel(userId: string, jobId: string) {
    // The worker honors "canceled" mid-run; a queued row is simply never claimed.
    const canceled = await prisma.cutRenderJob.updateMany({
      where: { id: jobId, userId, state: { in: ["queued", "running"] } },
      data: { state: "canceled" },
    });
    // 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 — except a borrowed
    // render's, which was the job's scratch and goes with the row.
    if (canceled.count === 0) {
      const row = await findJob(userId, jobId);
      if (row && ["done", "error", "canceled"].includes(row.state)) {
        await prisma.cutRenderJob.update({ where: { id: row.id }, data: { state: "dismissed" } });
        if (row.outputKey?.startsWith(overlayPrefix(userId))) await del([row.outputKey]);
      }
    }
    return Response.json({ ok: true });
  },

  /**
   * Claim a name and a destination for an export the browser renders itself.
   *
   * The gates a queued render passes on its way in have to be passed here too —
   * the concurrent-render cap and the storage margin — because a browser render
   * is still a render this account asked for and still lands as a stored file.
   * The name is deduped here, where the rows are, exactly as it is for the
   * worker.
   */
  async exportClientPresign(userId: string, req: Request) {
    try {
      const body = (await req.json()) as { projectId?: string; outName?: string; bytes?: number; stems?: boolean };
      const claim: ExportFiles = body.stems === true ? "fileAndStems" : "file";
      const projectId = body.projectId;
      if (!projectId) return err("projectId is required.", 400);
      if (!(await getProject(userId, projectId))) return err(new UserError("project_not_found", "Project not found."), 400);
      const capped = await renderJobCheck(userId);
      if (capped) return capped;
      // The size the render is heading for, from the same model the export
      // dialog showed. A render an account has no room for is refused here,
      // before minutes of encoding; what actually lands is weighed again at
      // completion, because an encoder spends what the footage needs.
      const estimate = Number.isFinite(body.bytes) && body.bytes! > 0 ? Math.round(body.bytes!) : 0;
      const over = await quotaCheck(userId, estimate, EXPORT_QUOTA_MARGIN);
      if (over) return over;
      // The name is claimed by writing the row, not just by reading the rows
      // that exist. `exportName` dedupes against stored objects and jobs, so a
      // second export started while this one renders has to see this one — two
      // tabs exporting the same project would otherwise both be handed
      // "export.mp4", the second upload would overwrite the first, and the
      // completion would then fail on the unique key with the render already
      // spent. The row is the reservation.
      const row = await prisma.$transaction(async (tx) => {
        const outName = await exportName(userId, projectId, body.outName ?? "export.mp4", undefined, tx, claim);
        return tx.cutRenderJob.create({
          data: {
            userId,
            projectId,
            kind: "export",
            // Rendering, in the tab rather than on the worker — which is why
            // nothing ever claims it.
            state: "running",
            progress: 0,
            spec: claim === "fileAndStems" ? { client: true, stems: true } : { client: true },
            outName,
          },
        });
      });
      const key = projectExportKey(userId, projectId, row.outName!);
      const type = containerOfName(row.outName!).mime;
      // The stems zip lands beside the file, under the name claimed with it.
      const stemsUrl = claim === "fileAndStems"
        ? await presignPut(projectExportKey(userId, projectId, stemsArchiveName(row.outName!)), STEMS_MIME)
        : undefined;
      return Response.json({
        jobId: row.id,
        key,
        outName: row.outName,
        type,
        url: await presignPut(key, type),
        ...(stemsUrl ? { stemsUrl } : {}),
      });
    } catch (e) {
      return caught(e, new UserError("export_could_not_start", "Could not start the export."));
    }
  },

  /**
   * Register a browser-rendered export that has finished uploading.
   *
   * The row is written already finished, because it is: the render happened in
   * the tab and the bytes are in the bucket before this is called. That is the
   * whole difference from a queued export — there is no state for the client to
   * poll towards, so the dock's next refresh simply finds a completed job.
   *
   * The object's size is read from the bucket rather than taken from the
   * client, since it is what the account's storage is charged.
   */
  async exportClientComplete(userId: string, req: Request) {
    try {
      const body = (await req.json()) as { jobId?: string };
      if (!body.jobId) return err("jobId is required.", 400);
      // The row the presign reserved carries the project and the name, so the
      // client cannot claim a different one at completion time.
      const row = await prisma.cutRenderJob.findFirst({
        where: { id: body.jobId, userId },
        select: { ...jobRowSelect, spec: true },
      });
      if (!row || row.kind !== "export" || !row.projectId || !row.outName) {
        return err(new UserError("export_not_found", "Export not found."), 400);
      }
      if (row.state === "canceled") return err(new UserError("export_canceled", "Export canceled."), 400);
      const { projectId, outName } = row;
      const key = projectExportKey(userId, projectId, outName);
      const object = await head(key);
      if (!object) return err(new UserError("export_not_uploaded", "The export was not uploaded."), 400);

      // A render that asked for stems uploaded them before the file. Each file
      // is its own row at its own size, so deleting one frees what it held.
      const files = [{ r2Key: key, fileName: outName, mime: containerOfName(outName).mime, bytes: object.bytes }];
      if (jobWantsStems(row.spec)) {
        const stemsName = stemsArchiveName(outName);
        const stemsKey = projectExportKey(userId, projectId, stemsName);
        const stemsObject = await head(stemsKey);
        if (!stemsObject) return err(new UserError("export_stems_not_uploaded", "The stems were not uploaded."), 400);
        files.push({ r2Key: stemsKey, fileName: stemsName, mime: STEMS_MIME, bytes: stemsObject.bytes });
      }
      const bytes = files.reduce((sum, f) => sum + f.bytes, 0);
      // The account is charged what landed, so the quota is checked against it.
      // A file past the ceiling is dropped rather than charged: the row would
      // otherwise put the account over its cap for good, and the bytes it holds
      // are the ones nothing else can free.
      const over = await quotaCheck(userId, bytes, EXPORT_QUOTA_MARGIN);
      if (over) {
        await dropUnregisteredExport(userId, row);
        await prisma.cutRenderJob.updateMany({
          where: { id: row.id, state: { in: ["running", "queued"] } },
          data: { state: "dismissed" },
        });
        return over;
      }
      await prisma.$transaction(async (tx) => {
        await tx.cutMediaObject.createMany({
          data: files.map((f) => ({
            ...f,
            userId,
            projectId,
            bytes: BigInt(f.bytes),
            kind: "export",
            uploadState: "complete",
          })),
        });
        await addUsage(tx, userId, bytes);
        await tx.cutRenderJob.update({
          where: { id: row.id },
          // A row the worker once mistook for its own may carry its error.
          data: { state: "done", progress: 1, outputKey: key, error: null },
        });
      });
      return Response.json({ id: row.id, outName });
    } catch (e) {
      return caught(e, new UserError("export_save_failed", "Could not save the export."));
    }
  },

  /**
   * A tab render's heartbeat: its progress so far, and a fresh updatedAt that
   * tells the worker's stale sweep the tab is still drawing. A claim whose tab
   * goes quiet for minutes is dismissed there.
   */
  async exportClientProgress(userId: string, jobId: string, req: Request) {
    try {
      const body = (await req.json().catch(() => ({}))) as { ratio?: unknown };
      const ratio = typeof body.ratio === "number" && Number.isFinite(body.ratio)
        ? Math.min(1, Math.max(0, body.ratio))
        : undefined;
      await prisma.cutRenderJob.updateMany({
        where: { id: jobId, userId, kind: "export", state: "running", spec: { path: ["client"], equals: true } },
        data: { updatedAt: new Date(), ...(ratio === undefined ? {} : { progress: ratio }) },
      });
      return Response.json({ ok: true });
    } catch (e) {
      return caught(e, new UserError("export_progress_failed", "Could not record the export's progress."));
    }
  },

  /**
   * Give back a name a browser render claimed but will not use.
   *
   * 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. 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 {
      const row = await prisma.cutRenderJob.findFirst({
        where: { id: jobId, userId },
        select: { ...jobRowSelect, spec: true },
      });
      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, new UserError("export_release_failed", "Could not release the export."));
    }
  },

  async exportFile(userId: string, jobId: string) {
    try {
      const row = await findJob(userId, jobId);
      if (!row || row.state !== "done" || !row.outputKey) {
        return new Response("Export not ready.", { status: 404 });
      }
      if (row.kind === "preview" && !row.outputKey.startsWith(overlayPrefix(userId))) {
        const artifact = await prisma.cutMediaObject.findUnique({ where: { r2Key: row.outputKey }, select: { id: true } });
        if (!artifact) return err(new UserError("preview_expired", "Preview expired. Render it again."), 410);
      }
      // A finished job's output never changes, so the redirect is cacheable.
      return redirect(
        mediaObjectUrl(row.outputKey, row.outName ? { downloadName: row.outName } : undefined),
        MEDIA_REDIRECT_HEADERS
      );
    } catch (e) {
      return caught(e, new UserError("export_not_ready", "Export not ready."));
    }
  },

  /** The exports-dock feed: every export job for this account, start order —
   * same view the engine's listAllJobs builds (previews stay internal). */
  async exportFeed(userId: string) {
    // Every open tab polls this for as long as the app is up, so it reads the
    // rows once and only the columns the cards show. The render spec stays
    // where it is: it carries the whole document a render was cut from, and
    // nothing here reads it.
    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) } },
        ],
      },
      orderBy: { createdAt: "asc" },
      select: {
        id: true,
        projectId: true,
        state: true,
        progress: true,
        outName: true,
        error: true,
        claimedAt: true,
        createdAt: true,
        updatedAt: true,
      },
    });
    // A browser render lives in a tab, and a tab can close mid-render. Nothing
    // 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: the row is dismissed (kept for the day's
    // count) and a file the tab uploaded without registering goes. They are
    // already in hand — a still-running row is in the feed by definition.
    const staleBefore = Date.now() - CLIENT_RENDER_WINDOW_MS;
    const stale = rows.filter(
      (r) => r.state === "running" && r.claimedAt === null && r.updatedAt.getTime() < staleBefore
    );
    for (const row of stale) {
      // The spec says whether the render landed stems; only these few rows read it.
      await prisma.cutRenderJob
        .findUnique({ where: { id: row.id }, select: { spec: true } })
        .then((found) => (found ? dropUnregisteredExport(userId, { ...row, spec: found.spec }) : undefined))
        .catch(() => {});
      await prisma.cutRenderJob
        .updateMany({ where: { id: row.id, state: "running" }, data: { state: "dismissed" } })
        .catch(() => {});
    }
    const swept = new Set(stale.map((r) => r.id));
    const live = rows.filter((r) => !swept.has(r.id));
    const projectIds = [...new Set(live.map((r) => r.projectId).filter((p): p is string => !!p))];
    const projects = projectIds.length
      ? await prisma.cutProject.findMany({
          where: { userId, id: { in: projectIds } },
          select: { id: true, name: true },
        })
      : [];
    const names = new Map(projects.map((p) => [p.id, p.name]));
    const failures = await rowFailures(live);
    return Response.json(
      live.map((r) => {
        const { status, error, ...failure } = engineStatus(r, failures.get(r.id));
        return {
          id: r.id,
          projectId: r.projectId ?? "",
          projectName: names.get(r.projectId ?? "") ?? "",
          status,
          progress: r.progress,
          outName: r.outName || undefined,
          error,
          ...failure,
          createdAt: r.createdAt.getTime(),
          startedAt: r.claimedAt?.getTime(),
        };
      })
    );
  },

  /** Queue a URL import — async on the cloud (the worker downloads), unlike the
   * engine's synchronous route. */
  async importUrl(userId: string, projectId: string, req: Request) {
    try {
      const { url, audio, key } = (await req.json()) as {
        url?: string;
        audio?: boolean;
        key?: string;
      };
      if (!url) return err("No URL provided.", 400);
      if (!validImportKey(key)) return err("Bad import key.", 400);
      const queued = await queueImportUrl(userId, projectId, { url, audio: audio === true, key });
      if (queued instanceof Response) return queued;
      return Response.json({ jobId: queued.id });
    } catch (e) {
      return caught(e, new UserError("url_import_failed", "Could not import that URL."));
    }
  },

  /** Queue a URL import into the shared library. No project owns it: the
   * worker lands the files under the account's library prefix and registers
   * the assets, and the client polls this job for them. */
  async importUrlToLibrary(userId: string, req: Request) {
    try {
      const { url, origin, audio, key } = (await req.json()) as {
        url?: string;
        origin?: string;
        audio?: boolean;
        key?: string;
      };
      if (!url) return err("No URL provided.", 400);
      if (!validImportKey(key)) return err("Bad import key.", 400);
      const open = await importJobFor(userId, key);
      if (open) return Response.json({ jobId: open.id });
      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,
            // carrying the origin the Camera Roll and Library filters read.
            ...(origin === "inspiration" ? { origin } : {}),
            ...(key ? { key } : {}),
          } as unknown as Prisma.InputJsonValue,
        },
      });
      wakeRenderWorker();
      return Response.json({ jobId: row.id });
    } catch (e) {
      return caught(e, new UserError("url_import_failed", "Could not import that URL."));
    }
  },

  /** Queue a media conversion: the worker rewrites one of the project's media
   * files as MP4 and registers it beside the original. */
  async convert(userId: string, projectId: string, req: Request) {
    try {
      const { file, maxHeight, mode: askedMode } = (await req.json()) as { file?: string; maxHeight?: number; mode?: unknown };
      if (!file) return err("file is required.", 400);
      const mode = convertModeIn(askedMode);
      if (!mode) return err("mode is fit or reencode.", 400);
      if (!(await getProject(userId, projectId))) return err(new UserError("project_not_found", "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 },
      });
      if (!source) return err(new UserError("media_file_missing", "Media file missing from project."), 404);
      const capped = await renderJobCheck(userId);
      if (capped) return capped;
      const row = await prisma.cutRenderJob.create({
        data: {
          userId,
          projectId,
          kind: "convert",
          spec: { file, ...(maxHeight ? { maxHeight } : {}), ...(mode === "reencode" ? { mode } : {}) } as unknown as Prisma.InputJsonValue,
        },
      });
      wakeRenderWorker();
      return Response.json({ jobId: row.id });
    } catch (e) {
      return caught(e, new UserError("convert_failed", "Could not convert that file."));
    }
  },

  /** Queue a preview proxy of a ProRes master, or of a heavy video at the
   * smaller `maxHeight` it asks for: the worker builds it and
   * registers it beside the master as a quota-exempt object. A proxy already
   * built answers at once, and a job already on its way answers with that
   * job, so a project copied to the cloud and then opened queues one.
   * `compat` asks for the compat proxy (lib/proxyNames.ts). */
  async proxy(userId: string, projectId: string, req: Request) {
    try {
      const { file, maxHeight: asked, compat: askedCompat } = (await req.json()) as { file?: string; maxHeight?: unknown; compat?: unknown };
      if (!file) return err("file is required.", 400);
      const compat = compatCoverIn(askedCompat);
      if (askedCompat !== undefined && !compat) return err("compat is audio or video.", 400);
      const maxHeight = typeof asked === "number" && Number.isFinite(asked) ? Math.round(Math.min(4320, Math.max(360, asked))) : undefined;
      if (!(await getProject(userId, projectId))) return err(new UserError("project_not_found", "Project not found."), 404);
      const source = await prisma.cutMediaObject.findFirst({
        where: { userId, projectId, fileName: file, kind: "media", uploadState: "complete" },
        select: { id: true },
      });
      if (!source) return err(new UserError("media_file_missing", "Media file missing from project."), 404);
      // A heavy video's request (it names a height) wants the light proxy
      // (lib/proxyNames.ts); a full-quality one built earlier doesn't answer it.
      const light = maxHeight !== undefined;
      const built = await builtProxy(userId, projectId, file, light, compat);
      if (built) return Response.json({ fileName: built.fileName, sizeBytes: Number(built.bytes) });
      const runningRows = await prisma.cutRenderJob.findMany({
        where: { userId, projectId, kind: "proxy", state: { in: ["queued", "running"] }, spec: { path: ["file"], equals: file } },
        select: { id: true, spec: true },
      });
      const running = runningRows.find((r) => sameProxyAsk(r.spec, light, compat));
      if (running) {
        wakeRenderWorker();
        return Response.json({ jobId: running.id });
      }
      // A master ffmpeg refused lately would be refused the same way: the
      // preview stays on the master, and no open costs a worker run. A build that failed for a passing reason retries at once.
      const { retryAfterHours } = await getGlobalSetting("cutProxy");
      const failedRows = await prisma.cutRenderJob.findMany({
        where: {
          userId,
          projectId,
          kind: "proxy",
          state: "error",
          createdAt: { gt: new Date(Date.now() - retryAfterHours * HOUR_MS) },
          spec: { path: ["file"], equals: file },
          result: { path: ["fault"], equals: PROXY_SOURCE_FAULT },
        },
        select: { spec: true },
      });
      if (failedRows.some((r) => sameProxyAsk(r.spec, light, compat))) {
        return err(new UserError("proxy_recently_failed", "The preview proxy could not be made from this file lately; the original plays instead."), 409);
      }
      const capped = await renderJobCheck(userId);
      if (capped) return capped;
      const row = await prisma.cutRenderJob.create({
        data: { userId, projectId, kind: "proxy", spec: { file, ...(maxHeight ? { maxHeight } : {}), ...(compat ? { compat } : {}) } as unknown as Prisma.InputJsonValue },
      });
      wakeRenderWorker();
      return Response.json({ jobId: row.id });
    } catch (e) {
      return caught(e, new UserError("proxy_failed", "Could not make the preview proxy."));
    }
  },

  /** Generic job poll for non-export kinds (import_url, convert, proxy). */
  async status(userId: string, jobId: string) {
    const row = await findJob(userId, jobId);
    if (!row) return err(new UserError("job_unknown", "Unknown job."), 404);
    if (needsWorker(row)) wakeRenderWorker();
    const settled =
      row.state === "done" || row.state === "error"
        ? (await prisma.cutRenderJob.findUnique({ where: { id: row.id }, select: { result: true } }))
            ?.result
        : null;
    const result = row.state === "done" ? settled : null;
    return Response.json({
      id: row.id,
      kind: row.kind,
      state: row.state,
      progress: row.progress,
      result: result ?? undefined,
      error: row.error ?? undefined,
      ...(row.state === "error" && row.error ? rowFailure(settled) : {}),
    });
  },
};