Skip to content

Open source CapCut alternative.

TypeScript

perf(site): serve public shares from the edge

David Lea2ded609cba6
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index f034d486..64d3e832 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -5,6 +5,7 @@ import Link from "next/link";
import { Clapperboard, Loader2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { apiFetch, setCutMode } from "@/cut/lib/backend";
+import { loadedDocVersion } from "@/cut/lib/backend/shared";
import { renderPreviewProxy } from "@/cut/lib/exportClient";
import { fileZoneAt, hasRefDrag } from "@/cut/lib/assetRef";
import { enrichAsset, importFileToProject } from "@/cut/lib/media";
@@ -26,6 +27,13 @@ import { Timeline } from "./Timeline";
import { TopBar } from "./TopBar";
import { ViewerTopBar } from "./ViewerTopBar";
+/** Bounds on the viewer's change poll. The server picks the interval inside
+ * this range from how long the owner has been idle; the floor keeps a live
+ * edit feeling live, the ceiling keeps a hidden tab or a settled project from
+ * polling forever. */
+const VIEWER_POLL_MIN_MS = 5_000;
+const VIEWER_POLL_MAX_MS = 300_000;
+
export function Editor({
projectId,
from,
@@ -89,37 +97,60 @@ export function Editor({
};
}, [projectId, viewer]);
- // Delayed follow of the owner's edits: poll the doc version every 10s and
- // reload on change, keeping the playhead. A 401/403/404 means the share was
- // revoked or narrowed — stop and say so.
+ // Delayed follow of the owner's edits: poll the doc version and reload on
+ // change, keeping the playhead. A 401/403/404 means the share was revoked or
+ // narrowed — stop and say so.
+ //
+ // The server sets the pace (x-cut-poll-after), because it knows how long the
+ // owner has been idle: an actively edited project answers in seconds, a
+ // settled one stretches to minutes so a shared link that a crowd is watching
+ // costs a handful of requests instead of six per viewer per minute. The
+ // response is cached at the edge for that same interval, so the poll usually
+ // never reaches the origin at all.
useEffect(() => {
if (!viewer) return;
- let last: string | null = null;
let stopped = false;
+ let timer: ReturnType<typeof setTimeout> | null = null;
const tick = async () => {
- if (stopped || document.hidden) return;
+ if (stopped) return;
+ let nextIn = document.hidden ? VIEWER_POLL_MAX_MS : VIEWER_POLL_MIN_MS;
try {
- const res = await apiFetch(`/api/cut/projects/${projectId}`, { method: "HEAD" });
- if ([401, 403, 404].includes(res.status)) {
- stopped = true;
- setShareGone(true);
- return;
- }
- if (!res.ok) return;
- const version = res.headers.get("x-cut-doc-version");
- if (version && last && version !== last) {
- const at = useEditor.getState().currentTime;
- await useEditor.getState().loadProject(projectId);
- for (const asset of useEditor.getState().assets) void enrichAsset(asset);
- useEditor.getState().seek(at);
+ if (!document.hidden) {
+ const res = await apiFetch(`/api/cut/projects/${projectId}`, { method: "HEAD" });
+ if ([401, 403, 404].includes(res.status)) {
+ stopped = true;
+ setShareGone(true);
+ return;
+ }
+ if (res.ok) {
+ const after = Number(res.headers.get("x-cut-poll-after"));
+ if (Number.isFinite(after) && after > 0) {
+ nextIn = Math.min(VIEWER_POLL_MAX_MS, Math.max(VIEWER_POLL_MIN_MS, after * 1000));
+ }
+ // Compare against the version the loaded doc reported, so a doc
+ // still coming from cache is fetched again on the next tick
+ // instead of the viewer settling on an older cut.
+ const version = res.headers.get("x-cut-doc-version");
+ const showing = loadedDocVersion(projectId);
+ if (version && showing && version !== showing) {
+ const at = useEditor.getState().currentTime;
+ await useEditor.getState().loadProject(projectId);
+ for (const asset of useEditor.getState().assets) void enrichAsset(asset);
+ useEditor.getState().seek(at);
+ }
+ }
}
- if (version) last = version;
} catch {
// Transient network failure — the next tick retries.
+ } finally {
+ if (!stopped) timer = setTimeout(() => void tick(), nextIn);
}
};
- const timer = setInterval(() => void tick(), 10_000);
- return () => clearInterval(timer);
+ timer = setTimeout(() => void tick(), VIEWER_POLL_MIN_MS);
+ return () => {
+ stopped = true;
+ if (timer) clearTimeout(timer);
+ };
}, [viewer, projectId]);
// A cloud save hit a newer stored version (another session's edits won).
@@ -144,6 +175,8 @@ export function Editor({
// Keep the project card's hover proxy fresh: rebuild it a few seconds after
// the cut settles. Best-effort and single-flight; skips when there's no cut.
+ // A shared project's link-preview card rides the same settle, so what the
+ // link unfurls with follows the edit instead of freezing at share time.
useEffect(() => {
if (viewer) return;
let timer: ReturnType<typeof setTimeout> | null = null;
@@ -152,20 +185,17 @@ export function Editor({
const s = useEditor.getState();
if (rendering || !s.loaded || s.projectId !== projectId || s.clips.length === 0) return;
rendering = true;
+ const doc = {
+ assets: s.assets,
+ clips: s.clips,
+ audioClips: s.audioClips,
+ overlays: s.overlays,
+ subtitles: s.subtitles,
+ fadeIn: s.fadeIn,
+ fadeOut: s.fadeOut,
+ };
try {
- await renderPreviewProxy(
- projectId,
- {
- assets: s.assets,
- clips: s.clips,
- audioClips: s.audioClips,
- overlays: s.overlays,
- subtitles: s.subtitles,
- fadeIn: s.fadeIn,
- fadeOut: s.fadeOut,
- },
- s.aspect
- );
+ await renderPreviewProxy(projectId, doc, s.aspect);
} finally {
rendering = false;
}
diff --git a/site/src/cut/lib/backend/shared.ts b/site/src/cut/lib/backend/shared.ts
index 03c35c4e..bdb29c4b 100644
--- a/site/src/cut/lib/backend/shared.ts
+++ b/site/src/cut/lib/backend/shared.ts
@@ -1,7 +1,9 @@
// The shared backend: a read-only view of someone else's cloud project,
// reached through the public /api/cut-shared/<token>/* surface. The token is
// the share link's id; the viewer page binds it before the editor mounts.
-// Reads only — the viewer never PUTs, so there is no version map here.
+// Reads only — the viewer never PUTs, so there is no write-conflict version
+// map here; the version it does keep is the one the last doc actually
+// delivered, which is what tells the change poll whether a reload landed.
import type { CutBackend } from "./types";
let token = "";
@@ -14,6 +16,31 @@ export function bindSharedBackend(next: string) {
const sharedPath = (path: string) =>
path.replace(/^\/api\/cut\//, `/api/cut-shared/${encodeURIComponent(token)}/`);
+// /projects/:id only — /projects/folders is the folder collection, not a doc.
+const PROJECT_DOC = /^\/api\/cut\/projects\/(?!folders$)([^/?]+)$/;
+
+const loadedVersions = new Map<string, string>();
+
+/** The doc version the viewer is actually showing for a project, as reported
+ * by the response that delivered it. The change poll compares against this
+ * rather than against the last version it saw announced: a cached doc can
+ * trail the version header the poll reads, and trusting the poll would leave
+ * the viewer holding an older cut while believing it was current. */
+export function loadedDocVersion(projectId: string): string | null {
+ return loadedVersions.get(projectId) ?? null;
+}
+
+async function sharedFetch(path: string, init?: RequestInit): Promise<Response> {
+ const res = await fetch(sharedPath(path), init);
+ const doc = PROJECT_DOC.exec(path);
+ const method = (init?.method ?? "GET").toUpperCase();
+ if (doc && method === "GET" && res.ok) {
+ const version = res.headers.get("x-cut-doc-version");
+ if (version) loadedVersions.set(decodeURIComponent(doc[1]), version);
+ }
+ return res;
+}
+
export const sharedBackend: CutBackend = {
kind: "shared",
caps: {
@@ -25,6 +52,6 @@ export const sharedBackend: CutBackend = {
revealInFinder: false,
watch: false,
},
- fetch: (path, init) => fetch(sharedPath(path), init),
+ fetch: sharedFetch,
url: (path) => sharedPath(path),
};
diff --git a/site/src/cut/server/cloud/media.ts b/site/src/cut/server/cloud/media.ts
index 468900b6..6032354f 100644
--- a/site/src/cut/server/cloud/media.ts
+++ b/site/src/cut/server/cloud/media.ts
@@ -4,7 +4,7 @@
// server like the engine's importImage.
import { prisma } from "@/lib/prisma";
import { getProject, takenMediaNames } from "./projects";
-import { GET_EXPIRY_SECONDS, head, presignGet, presignPut, projectMediaKey, putObject } from "./r2";
+import { head, presignGet, presignGetLifetime, presignPut, projectMediaKey, putObject } from "./r2";
import { addUsage, quotaCheck } from "./usage";
import { caught, dedupeName, err, safeFileName } from "./util";
@@ -132,7 +132,7 @@ export const mediaCloud = {
url: await presignGet(projectMediaKey(userId, i.projectId!, safeFileName(i.fileName!))),
}))
);
- return Response.json({ urls, expiresIn: GET_EXPIRY_SECONDS });
+ return Response.json({ urls, expiresIn: presignGetLifetime() });
} catch (e) {
return caught(e, "Could not sign the media URLs.");
}
diff --git a/site/src/cut/server/cloud/r2.ts b/site/src/cut/server/cloud/r2.ts
index e13d2d47..cc602e17 100644
--- a/site/src/cut/server/cloud/r2.ts
+++ b/site/src/cut/server/cloud/r2.ts
@@ -14,7 +14,10 @@ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const R2_BUCKET = "donkey-cut";
const PUT_EXPIRY_SECONDS = 60 * 60; // 1h — the client uploads right after presigning
-export const GET_EXPIRY_SECONDS = 24 * 60 * 60; // 24h — hydrated asset URLs live a session
+// 24h from the signing window's start (see signingWindowStart) — hydrated
+// asset URLs live a session. Clients should refresh against
+// presignGetLifetime(), which subtracts the elapsed part of the window.
+export const GET_EXPIRY_SECONDS = 24 * 60 * 60;
export class R2NotConfiguredError extends Error {
constructor() {
@@ -59,6 +62,29 @@ export function presignPut(key: string, mime: string): Promise<string> {
);
}
+/** Signatures are minted on window boundaries rather than at the current
+ * instant, so the same object presigns to the same URL for everyone asking
+ * within the window. A signature that changed per request made every media
+ * URL unique, which meant the browser cache (and any cache in front of it)
+ * could never reuse a byte — worst on a shared link, where many viewers pull
+ * the same objects and one viewer re-pulls them on every reload. */
+const SIGNING_WINDOW_SECONDS = 60 * 60; // 1h
+
+/** Start of the signing window `at` falls in. Exported for the callers that
+ * need to tell a client how long a URL stays good. */
+export function signingWindowStart(at: number = Date.now()): Date {
+ const ms = SIGNING_WINDOW_SECONDS * 1000;
+ return new Date(Math.floor(at / ms) * ms);
+}
+
+/** Seconds a URL minted now is still valid for: the tail of its window plus
+ * the expiry. Shorter than GET_EXPIRY_SECONDS, and it is what clients should
+ * refresh against. */
+export function presignGetLifetime(at: number = Date.now()): number {
+ const elapsed = (at - signingWindowStart(at).getTime()) / 1000;
+ return Math.round(GET_EXPIRY_SECONDS - elapsed);
+}
+
export function presignGet(key: string, downloadName?: string): Promise<string> {
return getSignedUrl(
r2(),
@@ -69,7 +95,7 @@ export function presignGet(key: string, downloadName?: string): Promise<string>
? { ResponseContentDisposition: `attachment; filename="${downloadName.replace(/"/g, "")}"` }
: {}),
}),
- { expiresIn: GET_EXPIRY_SECONDS }
+ { expiresIn: GET_EXPIRY_SECONDS, signingDate: signingWindowStart() }
);
}
diff --git a/site/src/cut/server/cloud/shareCache.ts b/site/src/cut/server/cloud/shareCache.ts
new file mode 100644
index 00000000..88a336a2
--- /dev/null
+++ b/site/src/cut/server/cloud/shareCache.ts
@@ -0,0 +1,72 @@
+// Edge caching for the public shared-viewer API.
+//
+// A share link is at its most useful in the window the owner has stopped
+// editing: they paste it somewhere and a crowd opens the same token at once.
+// So the cache lifetime tracks how long the project has been still — a doc
+// saved seconds ago is served near-live, one untouched for an hour is served
+// from the edge for minutes. `stale-while-revalidate` keeps every viewer off
+// the origin path either way: the edge answers immediately and refreshes
+// behind the request.
+//
+// Only public shares are cacheable. A restricted share's response depends on
+// the viewer's session cookie, so it must never land in a shared cache entry.
+import type { ShareRow } from "./sharedView";
+
+/** Bounds of the adaptive window, in seconds. */
+const MIN_TTL = 5;
+const MAX_TTL = 300;
+/** Ratio of idle time to cache lifetime: still for 20 minutes → cached a
+ * minute. Linear so there is no cliff for the client's poll interval to
+ * oscillate across. */
+const IDLE_DIVISOR = 20;
+/** The access decision itself (share meta) rides a shorter leash so revoking
+ * a link takes effect within the minute. */
+const META_MAX_TTL = 60;
+/** How long the edge may keep serving a stale copy while it refreshes. */
+const STALE_WHILE_REVALIDATE = 86400;
+
+/** Seconds of cache lifetime earned by a doc last written at `updatedAt`. */
+export function shareTtlSeconds(updatedAt: Date | null | undefined, cap = MAX_TTL): number {
+ if (!updatedAt) return MIN_TTL;
+ const idleSeconds = Math.max(0, (Date.now() - updatedAt.getTime()) / 1000);
+ return Math.round(Math.min(cap, Math.max(MIN_TTL, idleSeconds / IDLE_DIVISOR)));
+}
+
+/** Cache headers for one shared response, plus the poll interval the viewer
+ * should adopt. Restricted shares get a no-store answer and the floor
+ * interval — they are session-dependent and cannot be shared between viewers.
+ */
+export function shareCacheHeaders(
+ share: Pick<ShareRow, "access">,
+ updatedAt: Date | null | undefined,
+ opts: { meta?: boolean } = {}
+): Record<string, string> {
+ const ttl = shareTtlSeconds(updatedAt, opts.meta ? META_MAX_TTL : MAX_TTL);
+ // The viewer's change poll runs on the doc's lifetime, not meta's shorter
+ // one: polling faster than the doc can change only burns requests.
+ const pollAfter = shareTtlSeconds(updatedAt);
+ if (share.access !== "public") {
+ return {
+ "Cache-Control": "private, no-store",
+ "x-cut-poll-after": String(pollAfter),
+ };
+ }
+ // No Vary on Cookie: a public share resolves before any session is read, so
+ // every viewer gets the same bytes. Varying would give each signed-in viewer
+ // a private cache entry and undo the caching entirely.
+ return {
+ "Cache-Control": `public, s-maxage=${ttl}, stale-while-revalidate=${STALE_WHILE_REVALIDATE}`,
+ "x-cut-poll-after": String(pollAfter),
+ };
+}
+
+/** Headers for a redirect to a signed media URL. The signature is minted in
+ * fixed windows (see r2.ts), so the redirect is reusable until the window
+ * turns over; keep it well inside that window. */
+export function shareRedirectHeaders(
+ share: Pick<ShareRow, "access">,
+ ttlSeconds: number
+): Record<string, string> {
+ if (share.access !== "public") return { "Cache-Control": "private, no-store" };
+ return { "Cache-Control": `public, s-maxage=${ttlSeconds}` };
+}
diff --git a/site/src/cut/server/cloud/sharedView.ts b/site/src/cut/server/cloud/sharedView.ts
index 9375d7a4..1cd6cbd2 100644
--- a/site/src/cut/server/cloud/sharedView.ts
+++ b/site/src/cut/server/cloud/sharedView.ts
@@ -7,11 +7,15 @@
import type { ProjectDoc, StoredAsset } from "@/cut/lib/types";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
-import { GET_EXPIRY_SECONDS, presignGet, projectMediaKey } from "./r2";
+import { presignGet, presignGetLifetime, projectMediaKey } from "./r2";
import { normalizeEmails, normalizeFeatures, type ShareFeatures } from "./share";
+import { shareCacheHeaders, shareRedirectHeaders } from "./shareCache";
import { caught, decodeFileParam, err, redirect } from "./util";
const PRESIGN_GET_BATCH_MAX = 500;
+/** How long a media redirect may be reused. Well inside the signing window so
+ * the URL it carries never expires before the redirect does. */
+const MEDIA_REDIRECT_TTL = 15 * 60;
export type ShareRow = NonNullable<
Awaited<ReturnType<typeof prisma.cutProjectShare.findUnique>>
@@ -95,12 +99,15 @@ export const sharedView = {
if (view instanceof Response) return view;
const row = await ownerProject(view.share);
if (!row) return err("Share not found.", 404);
- return Response.json({
- projectId: view.share.projectId,
- name: row.name,
- access: view.share.access,
- features: view.features,
- });
+ return Response.json(
+ {
+ projectId: view.share.projectId,
+ name: row.name,
+ access: view.share.access,
+ features: view.features,
+ },
+ { headers: shareCacheHeaders(view.share, row.updatedAt, { meta: true }) }
+ );
},
async doc(token: string, id: string, req: Request) {
@@ -113,15 +120,23 @@ export const sharedView = {
if (req.method === "HEAD") {
const meta = await prisma.cutProject.findFirst({
where: { id: view.share.projectId, userId: view.share.userId },
- select: { version: true },
+ select: { version: true, updatedAt: true },
});
if (!meta) return err("Project not found.", 404);
- return new Response(null, { headers: { "x-cut-doc-version": String(meta.version) } });
+ return new Response(null, {
+ headers: {
+ "x-cut-doc-version": String(meta.version),
+ ...shareCacheHeaders(view.share, meta.updatedAt),
+ },
+ });
}
const row = await ownerProject(view.share);
if (!row) return err("Project not found.", 404);
return Response.json(filterDocForShare(row.doc as unknown as ProjectDoc, view.features), {
- headers: { "x-cut-doc-version": String(row.version) },
+ headers: {
+ "x-cut-doc-version": String(row.version),
+ ...shareCacheHeaders(view.share, row.updatedAt),
+ },
});
},
@@ -133,7 +148,10 @@ export const sharedView = {
const fileName = decodeFileParam(file);
const allowed = await allowedFileNames(view.share, view.features);
if (!allowed.has(fileName)) return err("Media not found.", 404);
- return redirect(await presignGet(projectMediaKey(view.share.userId, id, fileName)));
+ return redirect(
+ await presignGet(projectMediaKey(view.share.userId, id, fileName)),
+ shareRedirectHeaders(view.share, MEDIA_REDIRECT_TTL)
+ );
} catch (e) {
return caught(e, "Bad request.", 400);
}
@@ -163,7 +181,7 @@ export const sharedView = {
url: await presignGet(projectMediaKey(view.share.userId, i.projectId!, i.fileName!)),
}))
);
- return Response.json({ urls, expiresIn: GET_EXPIRY_SECONDS });
+ return Response.json({ urls, expiresIn: presignGetLifetime() });
} catch (e) {
return caught(e, "Could not sign the media URLs.");
}
@@ -176,9 +194,12 @@ export const sharedView = {
const rows = await prisma.cutChatThread.findMany({
where: { userId: view.share.userId, projectId: id },
orderBy: { updatedAt: "desc" },
- select: { data: true },
+ select: { data: true, updatedAt: true },
});
- return Response.json(rows.map((r) => r.data));
+ return Response.json(
+ rows.map((r) => r.data),
+ { headers: shareCacheHeaders(view.share, rows[0]?.updatedAt) }
+ );
},
async preview(token: string, id: string, req: Request) {
@@ -188,7 +209,10 @@ export const sharedView = {
if (id !== view.share.projectId) return err("Not found.", 404);
const row = await ownerProject(view.share);
if (!row?.previewKey) return new Response("Not found.", { status: 404 });
- return redirect(await presignGet(row.previewKey));
+ return redirect(
+ await presignGet(row.previewKey),
+ shareRedirectHeaders(view.share, MEDIA_REDIRECT_TTL)
+ );
} catch (e) {
return caught(e, "Bad request.", 400);
}
diff --git a/site/src/cut/server/cloud/util.ts b/site/src/cut/server/cloud/util.ts
index edaf9ebb..db23e81f 100644
--- a/site/src/cut/server/cloud/util.ts
+++ b/site/src/cut/server/cloud/util.ts
@@ -9,8 +9,8 @@ export const caught = (e: unknown, fallback: string, status = 500) =>
? err(e.message, 500)
: err(e instanceof Error ? e.message : fallback, status);
-export const redirect = (url: string) =>
- new Response(null, { status: 302, headers: { Location: url } });
+export const redirect = (url: string, headers: Record<string, string> = {}) =>
+ new Response(null, { status: 302, headers: { Location: url, ...headers } });
/** Sanitize an upload name the way the engine's saveMedia does. */
export function safeFileName(original: string): string {