Skip to content

Open source CapCut alternative.

TypeScript

feat(cut): record and sweep ladders through Workers KV [rebuild]

David Le7d17e4365e9f
diff --git a/site/.env.example b/site/.env.example
index f67ad5d1..6e59fec2 100644
--- a/site/.env.example
+++ b/site/.env.example
@@ -66,3 +66,14 @@ CUT_RENDER_WAKE_SECRET="replace-with-wake-secret"
# Worker's own CUT_MEDIA_SIGNING_SECRET (openssl rand -hex 32); the hostname is
# code, in src/cut/lib/hosts.ts.
CUT_MEDIA_SIGNING_SECRET="replace-with-media-signing-secret"
+
+# Cut share streaming. Records which HLS ladder version a project publishes, in
+# a Workers KV namespace the code creates on first write and then finds by
+# title (src/cut/server/cloud/ladderStore.ts) — so this token is the whole
+# setup. Needs Workers KV read+write on the account in R2_ACCOUNT_ID. Required
+# wherever shares stream: without it a ladder render fails outright and the
+# stream route logs and 5xxs, so a misconfiguration is visible rather than
+# silent — viewers meanwhile fall back to the project's flattened proxy. The
+# render worker holds the same value as a Worker secret, since the container
+# writes the pointer when a ladder finishes.
+CLOUDFLARE_KV_API_TOKEN="replace-with-kv-api-token"
diff --git a/site/src/cut/server/cloud/gc.ts b/site/src/cut/server/cloud/gc.ts
index 21615690..208e19bb 100644
--- a/site/src/cut/server/cloud/gc.ts
+++ b/site/src/cut/server/cloud/gc.ts
@@ -6,9 +6,10 @@
import { prisma } from "@/lib/prisma";
import { graceDeadline } from "./grace";
import { cutLimitsFor, FREE_STORAGE_BYTES } from "./limits";
+import { collectable, listSweepableLadders, pruneLadder, readLadder } from "./ladderStore";
import { deleteLibraryAssetCascade } from "./library";
import { deleteProjectCascade } from "./projects";
-import { del, INFERENCE_PREFIX, listOlderThan } from "./r2";
+import { del, deletePrefix, INFERENCE_PREFIX, listOlderThan, projectHlsRoot } from "./r2";
import { addUsage } from "./usage";
const PENDING_MAX_AGE_MS = 24 * 60 * 60 * 1000;
@@ -23,8 +24,65 @@ const RECLAIM_SCAN_LIMIT = 500;
const RECLAIM_MAX_USERS = 10;
const RECLAIM_MAX_DELETES_PER_USER = 25;
+// A re-rendered HLS ladder is written to a NEW version prefix so viewers on
+// the old one keep playing off the edge cache. That makes the previous ladder
+// garbage the moment the new one publishes — but not immediately collectable,
+// because someone may still be watching it. A day of grace clears any single
+// sitting, timed from when the version was RETIRED (the record carries that
+// stamp) rather than from when its bytes were written, which for a ladder built
+// weeks ago is already long past and would mean no grace at all.
+const HLS_RETIRED_GRACE_MS = 24 * 60 * 60 * 1000;
+// A version claimed but never published belongs to a render that is either
+// still going or dead. The longest a ladder can legitimately take is bounded by
+// the worker's own job lifetime, so past this it is a dead render's leftovers.
+const HLS_PENDING_TIMEOUT_MS = 6 * 60 * 60 * 1000;
+
type ReclaimPlan = { projects: string[]; assets: string[]; bytes: number };
+/**
+ * Drop ladder versions a project has moved on from, and the leftovers of
+ * renders that died partway.
+ *
+ * Ladders carry no media rows and no storage quota, so the record in KV is the
+ * only index of them and this is a pure prefix delete. Two clocks decide what
+ * goes: a retired version leaves a day after it stopped being current, and a
+ * pending version — one claimed before upload whose render never published —
+ * leaves once it is too old to still be running.
+ *
+ * The work scales with the garbage, not the project count: only records that
+ * carry retired or pending versions are listed at all, and a swept record drops
+ * out of that set. So there is no per-run project cap to strand the tail of the
+ * namespace behind the same first hundred keys every night.
+ */
+async function sweepStaleLadders() {
+ const out = { projects: 0, versions: 0, objects: 0, failed: 0 };
+ const now = Date.now();
+ for (const { projectId } of await listSweepableLadders()) {
+ try {
+ const record = await readLadder(projectId);
+ if (!record) continue;
+ const drop = collectable(record, now, HLS_RETIRED_GRACE_MS, HLS_PENDING_TIMEOUT_MS);
+ if (drop.length === 0) continue;
+ const root = projectHlsRoot(record.userId, projectId);
+ const dropped = new Set<string>();
+ for (const version of drop) {
+ out.objects += await deletePrefix(`${root}${version}/`);
+ dropped.add(version);
+ }
+ // Only now does the record forget them: pruning first would unindex the
+ // objects if the delete then failed.
+ await pruneLadder(projectId, record, dropped);
+ out.projects += 1;
+ out.versions += dropped.size;
+ } catch {
+ // One project's sweep failing must not fail the cron, and the record
+ // still names its garbage, so the next run tries again.
+ out.failed += 1;
+ }
+ }
+ return out;
+}
+
/** 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
@@ -251,6 +309,14 @@ export async function runGc(): Promise<Response> {
).catch(() => [] as string[]);
await del(scratch);
+ // Guarded like the prefix sweeps above it: the ladder store is optional
+ // infrastructure whose loss costs a re-render, so a missing token or an
+ // unreachable KV must not take down the run that reclaims storage.
+ const ladders = await sweepStaleLadders().catch((e: unknown) => {
+ console.error("[cut-gc] ladder sweep failed:", e instanceof Error ? e.message : e);
+ return { projects: 0, versions: 0, objects: 0, failed: 1 };
+ });
+
const reclaimed = await reclaimOverQuota();
return Response.json({
@@ -258,6 +324,10 @@ export async function runGc(): Promise<Response> {
orphanedMedia: orphans.length,
inferenceScratch: scratch.length,
renderJobs: jobs.count,
+ staleLadderProjects: ladders.projects,
+ staleLadderVersions: ladders.versions,
+ staleLadderObjects: ladders.objects,
+ staleLadderFailures: ladders.failed,
reclaimedUsers: reclaimed.users,
reclaimedProjects: reclaimed.projects,
reclaimedLibraryAssets: reclaimed.libraryAssets,
diff --git a/site/src/cut/server/cloud/ladderStore.test.ts b/site/src/cut/server/cloud/ladderStore.test.ts
new file mode 100644
index 00000000..d5698879
--- /dev/null
+++ b/site/src/cut/server/cloud/ladderStore.test.ts
@@ -0,0 +1,154 @@
+import { describe, expect, test } from "bun:test";
+
+import {
+ collectable,
+ withPending,
+ withPublished,
+ type LadderRecord,
+ type LadderVersion,
+} from "./ladderStore";
+
+const USER = "user1";
+const version = (v: string, over: Partial<LadderVersion> = {}): LadderVersion => ({
+ version: v,
+ duration: 120,
+ burnedSubtitles: false,
+ ...over,
+});
+
+const HOUR = 60 * 60 * 1000;
+const DAY = 24 * HOUR;
+
+describe("claiming a version", () => {
+ test("a version is indexed before any of its bytes exist", () => {
+ // The record is the only index of ladder trees. A version that uploaded
+ // before being named here would be invisible to every sweep if the job
+ // then died, leaking a whole cut's worth of segments with nothing left
+ // that could find them.
+ const next = withPending({ userId: USER }, USER, "v1", 1000);
+ expect(next.pending).toEqual([{ version: "v1", at: 1000 }]);
+ });
+
+ test("a retried version is re-stamped, not duplicated", () => {
+ const first = withPending({ userId: USER }, USER, "v1", 1000);
+ const again = withPending(first, USER, "v1", 5000);
+ expect(again.pending).toEqual([{ version: "v1", at: 5000 }]);
+ });
+
+ test("claiming leaves what is already published alone", () => {
+ const live: LadderRecord = { userId: USER, current: version("v1") };
+ expect(withPending(live, USER, "v2", 1000).current).toEqual(version("v1"));
+ });
+});
+
+describe("publishing a version", () => {
+ test("the replaced version is retired at the moment it was replaced", () => {
+ // Not at the moment its bytes were written — that is the clock the sweep's
+ // grace has to run on, and a ladder built weeks ago is already long past
+ // any age-based cutoff.
+ const live: LadderRecord = { userId: USER, current: version("v1") };
+ const next = withPublished(live, USER, version("v2"), 9_000);
+ expect(next.retired).toEqual([{ version: "v1", at: 9_000 }]);
+ expect(next.current?.version).toBe("v2");
+ });
+
+ test("publishing clears its own pending claim", () => {
+ const claimed = withPending({ userId: USER }, USER, "v1", 1000);
+ expect(withPublished(claimed, USER, version("v1"), 2000).pending).toEqual([]);
+ });
+
+ test("republishing the same version retires nothing", () => {
+ // The two-pass ladder publishes twice under one version; the second must
+ // not retire the ladder it is still writing.
+ const live: LadderRecord = { userId: USER, current: version("v1") };
+ expect(withPublished(live, USER, version("v1", { duration: 300 }), 9_000).retired).toEqual([]);
+ });
+
+ test("a first publish retires nothing", () => {
+ expect(withPublished({ userId: USER }, USER, version("v1"), 1000).retired).toEqual([]);
+ });
+
+ test("the retired list is bounded", () => {
+ let record: LadderRecord = { userId: USER };
+ for (let i = 0; i < 40; i++) record = withPublished(record, USER, version(`v${i}`), i * 1000);
+ expect(record.retired!.length).toBeLessThanOrEqual(12);
+ // What it keeps is the most recent, which is what still has viewers.
+ expect(record.retired!.at(-1)!.version).toBe("v38");
+ });
+});
+
+describe("what a sweep may collect", () => {
+ const record: LadderRecord = {
+ userId: USER,
+ current: version("v3"),
+ retired: [
+ { version: "v1", at: 0 },
+ { version: "v2", at: 0 },
+ ],
+ pending: [{ version: "v4", at: 0 }],
+ };
+
+ test("nothing goes before its grace has run", () => {
+ expect(collectable(record, HOUR, DAY, 6 * HOUR)).toEqual([]);
+ });
+
+ test("a retired version survives until its own grace has run", () => {
+ // The grace exists for the viewer holding that ladder mid-watch, so the
+ // two clocks are checked apart: retired is the slower one.
+ const retiredOnly: LadderRecord = {
+ userId: USER,
+ current: version("v3"),
+ retired: [{ version: "v1", at: 0 }],
+ };
+ expect(collectable(retiredOnly, DAY - 1, DAY, 6 * HOUR)).toEqual([]);
+ expect(collectable(retiredOnly, DAY, DAY, 6 * HOUR)).toEqual(["v1"]);
+ });
+
+ test("a pending version goes once it is too old to still be rendering", () => {
+ // Its render died partway; the segments it uploaded are garbage nothing
+ // else in the system can find.
+ const pendingOnly: LadderRecord = {
+ userId: USER,
+ current: version("v3"),
+ pending: [{ version: "v4", at: 0 }],
+ };
+ expect(collectable(pendingOnly, 6 * HOUR - 1, DAY, 6 * HOUR)).toEqual([]);
+ expect(collectable(pendingOnly, 6 * HOUR, DAY, 6 * HOUR)).toEqual(["v4"]);
+ });
+
+ test("both clocks run independently", () => {
+ // Past the retired grace, everything aged out of either list goes.
+ expect(collectable(record, DAY, DAY, 6 * HOUR).sort()).toEqual(["v1", "v2", "v4"]);
+ });
+
+ test("a live render's claim is left alone", () => {
+ expect(collectable(record, HOUR, DAY, 6 * HOUR)).not.toContain("v4");
+ });
+
+ test("what is being served is never collectable", () => {
+ // Even if it somehow appears in both lists — a record written by an older
+ // build, a publish that raced a retire — the current tree stays.
+ const confused: LadderRecord = {
+ ...record,
+ retired: [...record.retired!, { version: "v3", at: 0 }],
+ pending: [...record.pending!, { version: "v3", at: 0 }],
+ };
+ expect(collectable(confused, 10 * DAY, DAY, 6 * HOUR)).not.toContain("v3");
+ });
+
+ test("a version listed twice is returned once", () => {
+ const dupe: LadderRecord = {
+ userId: USER,
+ current: version("v9"),
+ retired: [{ version: "v1", at: 0 }],
+ pending: [{ version: "v1", at: 0 }],
+ };
+ expect(collectable(dupe, 10 * DAY, DAY, 6 * HOUR)).toEqual(["v1"]);
+ });
+
+ test("a record with nothing retired or pending collects nothing", () => {
+ expect(collectable({ userId: USER, current: version("v1") }, 10 * DAY, DAY, 6 * HOUR)).toEqual(
+ []
+ );
+ });
+});
diff --git a/site/src/cut/server/cloud/ladderStore.ts b/site/src/cut/server/cloud/ladderStore.ts
new file mode 100644
index 00000000..26dd317b
--- /dev/null
+++ b/site/src/cut/server/cloud/ladderStore.ts
@@ -0,0 +1,355 @@
+// Where a project's HLS ladders are recorded.
+//
+// This is derived state, not user data: it says which ladder is current and
+// which are on their way out, and losing it costs a re-render. So it lives in
+// Cloudflare KV rather than in the project row — no schema to migrate, and a
+// record that is rebuildable by construction.
+//
+// The record tracks every tree the project has ever started, not just the one
+// it serves. That is the load-bearing part. A ladder is hundreds of R2 objects
+// with no database rows, and this record is the only index of them, so a tree
+// that never made it in would be invisible to every sweep and leak forever.
+// Hence `pending`: a version is written here BEFORE its first byte is uploaded,
+// so a job that dies mid-upload still leaves a trail. And hence `retired`,
+// which carries the moment a version was replaced — the grace a viewer gets is
+// measured from when their ladder stopped being current, not from when its
+// bytes happened to be written.
+//
+// Neither writer runs inside a Worker (the site is on Vercel, the render worker
+// is a container), so both reach KV over the REST API, the same way copyQueue
+// publishes to Cloudflare Queues. The namespace is addressed by title and
+// resolved once per process; only the token comes from the environment.
+const KV_NAMESPACE_TITLE = "donkey-cut-ladders";
+
+const KEY_PREFIX = "hls:";
+const ladderKey = (projectId: string) => `${KEY_PREFIX}${projectId}`;
+
+/** How many retired versions a record keeps. The sweep clears them within a
+ * day, so this only has to survive a burst of re-renders; past it the oldest
+ * are dropped from the record and collected by the unindexed-tree sweep. */
+const MAX_RETIRED = 12;
+
+/** One published ladder. */
+export interface LadderVersion {
+ /** Path segment the ladder's objects live under. */
+ version: string;
+ /** Seconds of cut, which sizes the viewer's access token. */
+ duration: number;
+ /**
+ * Whether captions are burned into these pixels.
+ *
+ * Recorded because it cannot be undone downstream: a share that does not
+ * grant Subtitles must not be served a render with the cue text in the
+ * frame, and by then it is pixels rather than a field to strip.
+ */
+ burnedSubtitles: boolean;
+}
+
+/** What a project's ladders look like. */
+export interface LadderRecord {
+ userId: string;
+ /** The ladder a share plays. Absent until the first one publishes. */
+ current?: LadderVersion;
+ /** Replaced ladders, with when they were replaced — the clock the sweep's
+ * grace period actually runs on. */
+ retired?: { version: string; at: number }[];
+ /** Versions whose upload began and never published. A live render owns one;
+ * one left behind by a dead render is garbage, told apart by age. */
+ pending?: { version: string; at: number }[];
+}
+
+/** What the key listing carries, so the sweep can skip projects with nothing to
+ * collect without fetching each record. Kept tiny: KV caps metadata at 1 KiB. */
+interface LadderMeta {
+ u: string;
+ /** Count of retired + pending entries; 0 means nothing to sweep. */
+ g: number;
+}
+
+/** A deployment without the KV token cannot record or find a ladder, so shares
+ * cannot stream at all. Carried as its own type for the same reason
+ * MediaNotConfiguredError is: the message names an environment variable, and
+ * routes answer in their own words rather than echoing it to whoever asked —
+ * including an anonymous share viewer. */
+export class LadderStoreNotConfiguredError extends Error {
+ constructor() {
+ super("CLOUDFLARE_KV_API_TOKEN is not set — share streams cannot be recorded or served");
+ }
+}
+
+function credentials(): { accountId: string; token: string } {
+ const accountId = process.env.R2_ACCOUNT_ID;
+ const token = process.env.CLOUDFLARE_KV_API_TOKEN;
+ if (!accountId || !token) throw new LadderStoreNotConfiguredError();
+ return { accountId, token };
+}
+
+let cachedNamespaceId: string | null = null;
+
+/** Find the namespace by title, creating it the first time. Creating it here
+ * rather than as a deploy step means the only setup a deployment needs is the
+ * token — and a token scoped to write KV can already make one. */
+async function namespaceId(accountId: string, token: string): Promise<string> {
+ if (cachedNamespaceId) return cachedNamespaceId;
+ const root = `https://api.cloudflare.com/client/v4/accounts/${accountId}/storage/kv/namespaces`;
+ const auth = { Authorization: `Bearer ${token}` };
+ // Paged: an account with many namespaces would otherwise hide ours past the
+ // first page and send this down the create path on every call.
+ for (let page = 1; page <= 10; page++) {
+ const res = await fetch(`${root}?per_page=100&page=${page}`, { headers: auth });
+ if (!res.ok) throw new Error(`KV namespace list failed: ${res.status}`);
+ const body = (await res.json()) as { result?: { id?: string; title?: string }[] };
+ const found = body.result?.find((n) => n.title === KV_NAMESPACE_TITLE);
+ if (found?.id) return (cachedNamespaceId = found.id);
+ if (!body.result || body.result.length < 100) break;
+ }
+ const created = await fetch(root, {
+ method: "POST",
+ headers: { ...auth, "Content-Type": "application/json" },
+ body: JSON.stringify({ title: KV_NAMESPACE_TITLE }),
+ });
+ if (created.ok) {
+ const body = (await created.json()) as { result?: { id?: string } };
+ if (body.result?.id) return (cachedNamespaceId = body.result.id);
+ }
+ // A racing writer may have created it between the scan and the attempt, so
+ // one re-scan decides between "someone beat us" and a real failure.
+ const retry = await fetch(`${root}?per_page=100`, { headers: auth });
+ if (retry.ok) {
+ const body = (await retry.json()) as { result?: { id?: string; title?: string }[] };
+ const found = body.result?.find((n) => n.title === KV_NAMESPACE_TITLE);
+ if (found?.id) return (cachedNamespaceId = found.id);
+ }
+ throw new Error(`KV namespace "${KV_NAMESPACE_TITLE}" could not be found or created`);
+}
+
+const base = (accountId: string, id: string) =>
+ `https://api.cloudflare.com/client/v4/accounts/${accountId}/storage/kv/namespaces/${id}`;
+
+function parseVersion(raw: unknown): LadderVersion | undefined {
+ const v = raw as Partial<LadderVersion> | undefined;
+ if (!v || typeof v.version !== "string" || !v.version) return undefined;
+ return {
+ version: v.version,
+ duration: Number(v.duration) || 0,
+ // Absent means unknown, and unknown has to read as "might have captions" —
+ // the safe direction for a boundary that cannot be re-checked later.
+ burnedSubtitles: v.burnedSubtitles !== false,
+ };
+}
+
+function parseStamps(raw: unknown): { version: string; at: number }[] {
+ if (!Array.isArray(raw)) return [];
+ return raw
+ .filter((e): e is { version: string; at: number } => {
+ const s = e as { version?: unknown; at?: unknown };
+ return typeof s?.version === "string" && !!s.version && Number.isFinite(Number(s?.at));
+ })
+ .map((e) => ({ version: e.version, at: Number(e.at) }));
+}
+
+function parseRecord(raw: unknown): LadderRecord | null {
+ const r = raw as Partial<LadderRecord> | null;
+ if (!r || typeof r.userId !== "string" || !r.userId) return null;
+ return {
+ userId: r.userId,
+ current: parseVersion(r.current),
+ retired: parseStamps(r.retired),
+ pending: parseStamps(r.pending),
+ };
+}
+
+const metaOf = (record: LadderRecord): LadderMeta => ({
+ u: record.userId,
+ g: (record.retired?.length ?? 0) + (record.pending?.length ?? 0),
+});
+
+async function put(projectId: string, record: LadderRecord): Promise<void> {
+ const { accountId, token } = credentials();
+ const id = await namespaceId(accountId, token);
+ const form = new FormData();
+ form.set("value", JSON.stringify(record));
+ // Metadata rides the key listing, which is what lets the sweep decide whether
+ // a project is worth any R2 calls without fetching its record.
+ form.set("metadata", JSON.stringify(metaOf(record)));
+ const res = await fetch(
+ `${base(accountId, id)}/values/${encodeURIComponent(ladderKey(projectId))}`,
+ { method: "PUT", headers: { Authorization: `Bearer ${token}` }, body: form }
+ );
+ if (!res.ok) throw new Error(`KV write failed: ${res.status}`);
+}
+
+/** A project's ladder record, or null when it has none.
+ *
+ * Null means exactly one thing — nothing recorded yet — so a caller can treat
+ * it as "still rendering". A misconfigured or unreachable store throws instead,
+ * and is never quietly reported as an absent ladder. */
+export async function readLadder(projectId: string): Promise<LadderRecord | null> {
+ const { accountId, token } = credentials();
+ const id = await namespaceId(accountId, token);
+ const res = await fetch(
+ `${base(accountId, id)}/values/${encodeURIComponent(ladderKey(projectId))}`,
+ { headers: { Authorization: `Bearer ${token}` } }
+ );
+ if (res.status === 404) return null;
+ if (!res.ok) throw new Error(`KV read failed: ${res.status}`);
+ return parseRecord(await res.json());
+}
+
+/**
+ * Claim a version before uploading a byte of it.
+ *
+ * This is what keeps a tree from ever being unindexed. The render mints a
+ * version, records it here, and only then uploads; if the container dies or the
+ * job is requeued, the half-written tree is still named in the record and the
+ * sweep collects it. Writing the pointer after the upload instead would leak
+ * the whole tree on every failed render, with nothing left that could find it.
+ */
+export async function beginLadder(
+ projectId: string,
+ userId: string,
+ version: string
+): Promise<void> {
+ const existing = (await readLadder(projectId)) ?? { userId };
+ await put(projectId, withPending(existing, userId, version, Date.now()));
+}
+
+/** `beginLadder`'s state transition, without the IO. */
+export function withPending(
+ existing: LadderRecord,
+ userId: string,
+ version: string,
+ at: number
+): LadderRecord {
+ return {
+ ...existing,
+ userId,
+ pending: [
+ ...(existing.pending ?? []).filter((p) => p.version !== version),
+ { version, at },
+ ],
+ };
+}
+
+/**
+ * Publish a finished ladder: it becomes current, whatever it replaced joins
+ * `retired` stamped with now, and it stops being pending.
+ *
+ * The stamp is the point. A viewer mid-watch is holding the version that just
+ * stopped being current, and the grace before its segments are deleted has to
+ * run from this moment — not from whenever those segments were written, which
+ * for a ladder built last week is already long past.
+ */
+export async function publishLadder(
+ projectId: string,
+ userId: string,
+ next: LadderVersion
+): Promise<void> {
+ const existing = (await readLadder(projectId)) ?? { userId };
+ await put(projectId, withPublished(existing, userId, next, Date.now()));
+}
+
+/** `publishLadder`'s state transition, without the IO. */
+export function withPublished(
+ existing: LadderRecord,
+ userId: string,
+ next: LadderVersion,
+ at: number
+): LadderRecord {
+ const retired = [
+ ...(existing.retired ?? []),
+ ...(existing.current && existing.current.version !== next.version
+ ? [{ version: existing.current.version, at }]
+ : []),
+ ].slice(-MAX_RETIRED);
+ return {
+ userId,
+ current: next,
+ retired,
+ pending: (existing.pending ?? []).filter((p) => p.version !== next.version),
+ };
+}
+
+/** Which versions a sweep at `now` should delete, given the two clocks: a
+ * retired version leaves after `retiredGraceMs` from the moment it stopped
+ * being current, a pending one after `pendingTimeoutMs` from when it was
+ * claimed. What is currently served is never in the set, whatever else the
+ * record says about it. */
+export function collectable(
+ record: LadderRecord,
+ now: number,
+ retiredGraceMs: number,
+ pendingTimeoutMs: number
+): string[] {
+ const expired = [
+ ...(record.retired ?? []).filter((r) => now - r.at >= retiredGraceMs),
+ ...(record.pending ?? []).filter((p) => now - p.at >= pendingTimeoutMs),
+ ];
+ return [
+ ...new Set(expired.map((e) => e.version).filter((v) => v !== record.current?.version)),
+ ];
+}
+
+/** Rewrite a record after a sweep has removed the trees it named. */
+export async function pruneLadder(
+ projectId: string,
+ record: LadderRecord,
+ dropped: Set<string>
+): Promise<void> {
+ await put(projectId, {
+ ...record,
+ retired: (record.retired ?? []).filter((r) => !dropped.has(r.version)),
+ pending: (record.pending ?? []).filter((p) => !dropped.has(p.version)),
+ });
+}
+
+/** Forget a project's ladders. Best-effort, and the one place that stays that
+ * way: it runs inside a project delete that has already removed the rows and
+ * the bytes, and failing a delete the user asked for is worse than a stray key
+ * that resolves to an empty prefix. */
+export async function deleteLadder(projectId: string): Promise<void> {
+ try {
+ const { accountId, token } = credentials();
+ const id = await namespaceId(accountId, token);
+ await fetch(`${base(accountId, id)}/values/${encodeURIComponent(ladderKey(projectId))}`, {
+ method: "DELETE",
+ headers: { Authorization: `Bearer ${token}` },
+ });
+ } catch {
+ // The sweep tolerates a record whose trees are already gone.
+ }
+}
+
+/**
+ * Every project with something to collect, read off the listing's metadata.
+ *
+ * Only records carrying retired or pending versions come back, so a run does
+ * work proportional to the garbage that exists rather than to the number of
+ * projects — and once a project is swept it drops out of this set. That is
+ * what lets the sweep page the whole namespace instead of stopping at a fixed
+ * number of projects and never reaching the rest.
+ */
+export async function listSweepableLadders(): Promise<{ projectId: string; userId: string }[]> {
+ const { accountId, token } = credentials();
+ const id = await namespaceId(accountId, token);
+ const out: { projectId: string; userId: string }[] = [];
+ let cursor = "";
+ do {
+ const url = new URL(`${base(accountId, id)}/keys`);
+ url.searchParams.set("prefix", KEY_PREFIX);
+ url.searchParams.set("limit", "1000");
+ if (cursor) url.searchParams.set("cursor", cursor);
+ const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
+ if (!res.ok) throw new Error(`KV list failed: ${res.status}`);
+ const body = (await res.json()) as {
+ result?: { name?: string; metadata?: LadderMeta }[];
+ result_info?: { cursor?: string };
+ };
+ for (const row of body.result ?? []) {
+ if (!row.name || !row.metadata?.u || !(Number(row.metadata.g) > 0)) continue;
+ out.push({ projectId: row.name.slice(KEY_PREFIX.length), userId: row.metadata.u });
+ }
+ cursor = body.result_info?.cursor ?? "";
+ } while (cursor);
+ return out;
+}
diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.ts
index 0ebce54d..60a6affc 100644
--- a/site/src/cut/server/cloud/projects.ts
+++ b/site/src/cut/server/cloud/projects.ts
@@ -3,8 +3,9 @@
import { normalizeAspect, type ProjectDoc, type ProjectFolder, type ProjectSummary } from "@/cut/lib/types";
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
+import { deleteLadder } from "./ladderStore";
import { mediaObjectUrl } from "./mediaCdn";
-import { del, projectExportKey, projectMediaKey } from "./r2";
+import { del, deletePrefix, projectExportKey, projectHlsRoot, projectMediaKey } from "./r2";
import { addUsage } from "./usage";
import { caught, decodeFileParam, err, redirect } from "./util";
@@ -109,6 +110,16 @@ export async function deleteProjectCascade(userId: string, id: string): Promise<
await addUsage(tx, userId, -freed);
});
await del(objects.map((o) => o.r2Key));
+ // The HLS ladders have no media rows at all — they are found by prefix and
+ // recorded in KV — so both have to be cleared by hand here. Neither affects
+ // `freed`: a ladder never counted toward the quota.
+ //
+ // The bytes go before the record does. A long 4K cut runs to tens of
+ // thousands of objects, so this pages rather than listing once; and pruning
+ // the record first would leave anything the delete missed with no index that
+ // could ever find it again.
+ await deletePrefix(projectHlsRoot(userId, id)).catch(() => 0);
+ await deleteLadder(id);
return freed;
}
diff --git a/site/src/cut/server/cloud/util.ts b/site/src/cut/server/cloud/util.ts
index 28a3ce15..71453b1e 100644
--- a/site/src/cut/server/cloud/util.ts
+++ b/site/src/cut/server/cloud/util.ts
@@ -1,4 +1,5 @@
import path from "node:path";
+import { LadderStoreNotConfiguredError } from "./ladderStore";
import { MediaNotConfiguredError } from "./mediaCdn";
import { R2NotConfiguredError } from "./r2";
@@ -14,6 +15,10 @@ export const caught = (e: unknown, fallback: string, status = 500) => {
console.error(e.message);
return err("Cloud media is unavailable.", 500);
}
+ if (e instanceof LadderStoreNotConfiguredError) {
+ console.error(e.message);
+ return err("Streaming is unavailable.", 500);
+ }
return err(e instanceof Error ? e.message : fallback, status);
};
diff --git a/site/src/cut/worker/README.md b/site/src/cut/worker/README.md
index d5faf0ce..44e8770d 100644
--- a/site/src/cut/worker/README.md
+++ b/site/src/cut/worker/README.md
@@ -132,3 +132,43 @@ drain serially instead of stampeding R2. One-time setup:
Without the queue env, the hosted API runs copies inline in the request —
fine for local dev, unthrottled in production.
+
+## Share streaming (HLS ladder)
+
+A shared project plays as an adaptive stream rather than a file, so an `hls`
+job renders the cut and packages it into a rung ladder under
+`cut/<user>/projects/<id>/hls/<version>/` in R2. Segments are served by the
+media handler above, through a token that covers the whole tree — see
+`../server/hlsLadder.ts` for why a single mp4 is the wrong shape here.
+
+What a project has published is recorded in **Workers KV**, not Postgres: it is
+derived state, and losing it costs a re-render and nothing else. Neither writer
+is a Worker (the site runs on Vercel, this render worker is a container), so
+both use the KV REST API.
+
+The record is more than a pointer, because it is the only index these trees
+have. A version is claimed there *before* its first byte uploads, so a render
+killed partway still leaves something the sweep can find; a published version
+displaces the previous one into a retired list stamped with the moment it was
+replaced, which is the clock its day of grace runs on. Only records carrying
+retired or pending versions are listed at all, so the nightly sweep does work
+proportional to the garbage rather than to how many projects exist.
+
+The only setup is the credential — `CLOUDFLARE_KV_API_TOKEN`, scoped to
+Workers KV read+write on the account in `R2_ACCOUNT_ID`, held both by the
+hosted site and as a Worker secret (`cf/worker.ts` passes it into the
+container). The namespace itself is created on first write and then found by
+title, so there is nothing to provision and no id to paste into
+`wrangler.jsonc`; the title lives in `../server/cloud/ladderStore.ts`.
+
+It is required, not optional, and its absence is loud where an operator will
+see it: a ladder render that cannot record where it landed fails its job with
+the reason on the row, and the stream route logs and answers 5xx rather than
+reporting "no ladder". What a viewer sees is separate — they fall back to the
+project's flattened preview proxy, because a broken deployment is not theirs to
+diagnose and a spinner helps nobody. The two are deliberately not the same
+signal: `readLadder` returning null means one thing only, that no ladder exists
+yet, and it never doubles as "something is broken".
+
+Ladders never count against a user's storage quota — they carry no media rows
+and are found and swept by prefix, the same way inference scratch is.
diff --git a/site/src/cut/worker/cf/worker.ts b/site/src/cut/worker/cf/worker.ts
index d061c647..2ff8a2e6 100644
--- a/site/src/cut/worker/cf/worker.ts
+++ b/site/src/cut/worker/cf/worker.ts
@@ -18,6 +18,7 @@ type WorkerEnv = MediaEnv & {
CUT_WAKE_SECRET: string;
CUT_COPY_EXECUTE_URL: string;
CUT_COPY_EXECUTE_SECRET: string;
+ CLOUDFLARE_KV_API_TOKEN: string;
};
// Minimal shapes for the queue consumer — this file stays off workers-types
@@ -52,6 +53,9 @@ export class CutRenderWorker extends Container<WorkerEnv> {
R2_ACCOUNT_ID: env.R2_ACCOUNT_ID,
R2_ACCESS_KEY_ID: env.R2_ACCESS_KEY_ID,
R2_SECRET_ACCESS_KEY: env.R2_SECRET_ACCESS_KEY,
+ // The container records a finished HLS ladder in KV. It is not a Worker,
+ // so it has no binding and goes over the REST API like the site does.
+ CLOUDFLARE_KV_API_TOKEN: env.CLOUDFLARE_KV_API_TOKEN,
};
}
}