Open source CapCut alternative.
TypeScript
feat(site): route shared media through the edge and re-mint on its own clock
David Lec846a9c5d8d1
diff --git a/site/.env.example b/site/.env.exampleindex c0495dcb..d8307aa8 100644--- a/site/.env.example+++ b/site/.env.example@@ -59,3 +59,11 @@ R2_SECRET_ACCESS_KEY="replace-with-r2-secret-access-key"# the worker by hand; it polls on its own).CUT_RENDER_WAKE_URL="replace-with-worker-wake-url"CUT_RENDER_WAKE_SECRET="replace-with-wake-secret"++# Shared-media edge delivery. With both set, a shared project's media is served+# from this host by the Cut Worker's R2 binding — cached at the edge, and+# revocable, because the token is ours and lives only minutes. The secret must+# match the Worker's CUT_MEDIA_SIGNING_SECRET. Leave unset (local dev) to+# presign R2 directly instead.+CUT_MEDIA_BASE_URL="https://media.donkeycut.com"+CUT_MEDIA_SIGNING_SECRET="replace-with-media-signing-secret"diff --git a/site/src/cut/lib/mediaLinks.ts b/site/src/cut/lib/mediaLinks.tsindex 0a8cd491..bbf7e42e 100644--- a/site/src/cut/lib/mediaLinks.ts+++ b/site/src/cut/lib/mediaLinks.ts@@ -1,38 +1,73 @@"use client";// Keeps a loaded project's media links working in a long-lived tab. Cloud and-// shared projects hydrate their assets with signed R2 URLs that expire after a-// day, so a laptop that sleeps past the expiry wakes to a project whose every-// <video>/<img> source 403s. Two guards close that hole:+// shared projects hydrate their assets with time-limited URLs, so a tab that+// outlives one holds a project whose every <video>/<img> source 403s. Three+// guards close that hole://-// - Eager refresh: when the tab becomes visible (or regains focus / network)-// within an hour of the signed batch's expiry, the batch re-mints and the-// store's asset URLs swap in place. Components and the preview engine both-// key their elements off asset.url, so the swap heals them on render.-// - Failure retry: a media element error on a signed URL forces a re-mint;-// an error on an API-route URL (whose 302 re-signs per request, so failures-// there are transient) reloads the element with a capped backoff.+// - Scheduled refresh: a timer re-mints ahead of expiry while the tab is+// visible. Lifetimes differ by a lot — a presigned R2 URL lasts a day, an+// edge media token a few minutes — so the lead is a fraction of the lifetime+// the mint reported rather than a fixed span.+// - Event refresh: becoming visible (or regaining focus / network) inside the+// lead re-mints too, which is what catches a laptop waking from sleep with+// every timer long since fired.+// - Failure retry: a media element error on a time-limited URL forces a+// re-mint; an error on an API-route URL (whose 302 re-signs per request, so+// failures there are transient) reloads the element with a capped backoff.//-// The store marks the batch at load; a global capture-phase error listener-// watches DOM elements, and the preview engine reports its detached decoders-// through reportMediaElementError.+// A re-mint swaps the store's asset URLs in place. Components and the preview+// engine both key their elements off asset.url, so the swap heals them on+// render. The store marks the batch at load; a global capture-phase error+// listener watches DOM elements, and the preview engine reports its detached+// decoders through reportMediaElementError.import { fetchSignedMediaUrls } from "./backend/cloud";import { mediaUrl } from "./types";-const REFRESH_LEAD_MS = 60 * 60 * 1000; // start re-minting an hour before expiry+/** Re-mint this far ahead of expiry, as a share of the whole lifetime, so a+ * five-minute token and a one-day one are both refreshed in good time. */+const REFRESH_LEAD_FRACTION = 1 / 3;+const MAX_REFRESH_LEAD_MS = 60 * 60 * 1000; // a day-long URL needn't lead by more+const MIN_REFRESH_LEAD_MS = 20_000; // …nor a short one by lessconst FORCED_GAP_MS = 15_000; // min gap between failure-driven re-mintsconst ELEMENT_RETRIES = 3;const ELEMENT_RETRY_BASE_MS = 1_000;const ATTEMPT_RESET_MS = 60_000; // an old failure streak doesn't cap a new one-let batch: { projectId: string; expiresAt: number } | null = null;+let batch: { projectId: string; expiresAt: number; lead: number } | null = null;let refreshing: Promise<void> | null = null;let lastForcedAt = 0;+let timer: ReturnType<typeof setTimeout> | null = null;-/** Record the signed batch minted for the loaded project (null expiry = the- * mint came back empty, so only self-healing route URLs are in play). */+function leadFor(expiresAt: number): number {+ const lifetime = Math.max(0, expiresAt - Date.now());+ return Math.min(+ MAX_REFRESH_LEAD_MS,+ Math.max(MIN_REFRESH_LEAD_MS, lifetime * REFRESH_LEAD_FRACTION)+ );+}++/** Wake at the top of the lead window. A hidden tab skips the mint — the+ * visibility handler picks it up on return — so a backgrounded project isn't+ * re-minting on a loop nobody is watching. */+function scheduleRefresh() {+ if (timer) clearTimeout(timer);+ timer = null;+ const b = batch;+ if (!b) return;+ const wait = Math.max(0, b.expiresAt - b.lead - Date.now());+ timer = setTimeout(() => {+ timer = null;+ if (typeof document !== "undefined" && document.visibilityState !== "visible") return;+ void refreshSignedUrls();+ }, wait);+}++/** Record the batch minted for the loaded project (null expiry = the mint came+ * back empty, so only self-healing route URLs are in play). */export function markSignedBatch(projectId: string, expiresAt: number | null) {- batch = expiresAt === null ? null : { projectId, expiresAt };+ batch = expiresAt === null ? null : { projectId, expiresAt, lead: leadFor(expiresAt) };+ scheduleRefresh();}/** Re-mint the loaded project's signed URLs and swap them into the store.@@ -42,7 +77,7 @@ function refreshSignedUrls(force = false): Promise<void> {refreshing = (async () => {const b = batch;if (!b) return;- if (!force && Date.now() < b.expiresAt - REFRESH_LEAD_MS) return;+ if (!force && Date.now() < b.expiresAt - b.lead) return;const { useEditor } = await import("./store");const s = useEditor.getState();if (!s.loaded || s.projectId !== b.projectId) return;@@ -58,17 +93,32 @@ function refreshSignedUrls(force = false): Promise<void> {urls.set(a.fileName, minted.urls.get(a.fileName) ?? mediaUrl(b.projectId, a.fileName));}st.applyMediaUrls(urls);- if (minted.expiresAt !== null) b.expiresAt = minted.expiresAt;+ if (minted.expiresAt !== null) {+ b.expiresAt = minted.expiresAt;+ b.lead = leadFor(minted.expiresAt);+ }// A failed mint left every asset on route URLs, which re-sign per request- // — nothing signed remains to track until the next load.+ // — nothing time-limited remains to track until the next load.else batch = null;})().finally(() => {refreshing = null;+ scheduleRefresh();});return refreshing;}-const isSignedUrl = (src: string) => src.includes("X-Amz-Signature=");+/** A URL whose access expires and can be re-minted: a presigned R2 URL, or an+ * edge media token (`?e=<expiry>&s=<signature>`). Both heal by re-minting the+ * batch; anything else does not. */+function isExpiringUrl(src: string): boolean {+ if (src.includes("X-Amz-Signature=")) return true;+ try {+ const params = new URL(src, window.location.origin).searchParams;+ return params.has("e") && params.has("s");+ } catch {+ return false;+ }+}const isCutApiUrl = (src: string) => src.includes("/api/cut");const attempts = new WeakMap<Element, { n: number; at: number }>();@@ -91,7 +141,7 @@ function retryElement(el: HTMLImageElement | HTMLMediaElement, src: string, atteexport function reportMediaElementError(el: HTMLImageElement | HTMLMediaElement) {const src = el instanceof HTMLImageElement ? el.src : el.currentSrc || el.src;if (!src || src.startsWith("blob:") || src.startsWith("data:")) return;- if (isSignedUrl(src)) {+ if (isExpiringUrl(src)) {if (Date.now() - lastForcedAt < FORCED_GAP_MS) return;lastForcedAt = Date.now();void refreshSignedUrls(true);@@ -110,7 +160,12 @@ export function reportMediaElementError(el: HTMLImageElement | HTMLMediaElement)if (typeof window !== "undefined") {const maybeRefresh = () => {if (document.visibilityState !== "visible") return;- if (batch && Date.now() >= batch.expiresAt - REFRESH_LEAD_MS) void refreshSignedUrls();+ if (!batch) return;+ if (Date.now() >= batch.expiresAt - batch.lead) void refreshSignedUrls();+ // Coming back to a tab whose timer fired while it was hidden: the mint is+ // still in the future, so re-arm rather than wait for an expiry that has+ // no wake-up left behind it.+ else if (!timer) scheduleRefresh();};document.addEventListener("visibilitychange", maybeRefresh);window.addEventListener("focus", maybeRefresh);diff --git a/site/src/cut/server/cloud/sharedView.ts b/site/src/cut/server/cloud/sharedView.tsindex 1cd6cbd2..ae3a9426 100644--- a/site/src/cut/server/cloud/sharedView.ts+++ b/site/src/cut/server/cloud/sharedView.ts@@ -7,16 +7,31 @@import type { ProjectDoc, StoredAsset } from "@/cut/lib/types";import { auth } from "@/lib/auth";import { prisma } from "@/lib/prisma";+import { MEDIA_TOKEN_TTL_SECONDS, mediaCdnEnabled, mediaCdnUrl } from "./mediaCdn";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. */+/** How long a media redirect may be reused. It has to stay inside the life of+ * the URL it carries, or the edge would keep handing out a dead link. */const MEDIA_REDIRECT_TTL = 15 * 60;+/** A viewer-facing URL for one of the owner's objects: the edge Worker when+ * this deployment has it configured, a presigned R2 URL otherwise. */+const sharedMediaUrl = (key: string): Promise<string> =>+ Promise.resolve(mediaCdnUrl(key) ?? presignGet(key));++/** Redirect lifetime that matches whichever URL kind was minted. */+const mediaRedirectTtl = () =>+ mediaCdnEnabled() ? Math.floor(MEDIA_TOKEN_TTL_SECONDS / 5) : MEDIA_REDIRECT_TTL;++/** What the client is told a media batch is good for, so it re-mints ahead of+ * expiry rather than after a 403. */+const mediaUrlLifetime = () =>+ mediaCdnEnabled() ? MEDIA_TOKEN_TTL_SECONDS : presignGetLifetime();+export type ShareRow = NonNullable<Awaited<ReturnType<typeof prisma.cutProjectShare.findUnique>>>;@@ -149,8 +164,8 @@ export const sharedView = {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)),- shareRedirectHeaders(view.share, MEDIA_REDIRECT_TTL)+ await sharedMediaUrl(projectMediaKey(view.share.userId, id, fileName)),+ shareRedirectHeaders(view.share, mediaRedirectTtl()));} catch (e) {return caught(e, "Bad request.", 400);@@ -178,10 +193,12 @@ export const sharedView = {.map(async (i) => ({projectId: i.projectId!,fileName: i.fileName!,- url: await presignGet(projectMediaKey(view.share.userId, i.projectId!, i.fileName!)),+ url: await sharedMediaUrl(+ projectMediaKey(view.share.userId, i.projectId!, i.fileName!)+ ),})));- return Response.json({ urls, expiresIn: presignGetLifetime() });+ return Response.json({ urls, expiresIn: mediaUrlLifetime() });} catch (e) {return caught(e, "Could not sign the media URLs.");}@@ -210,8 +227,8 @@ export const sharedView = {const row = await ownerProject(view.share);if (!row?.previewKey) return new Response("Not found.", { status: 404 });return redirect(- await presignGet(row.previewKey),- shareRedirectHeaders(view.share, MEDIA_REDIRECT_TTL)+ await sharedMediaUrl(row.previewKey),+ shareRedirectHeaders(view.share, mediaRedirectTtl()));} catch (e) {return caught(e, "Bad request.", 400);diff --git a/site/src/cut/worker/cf/worker.ts b/site/src/cut/worker/cf/worker.tsindex 33050b48..c397a97f 100644--- a/site/src/cut/worker/cf/worker.ts+++ b/site/src/cut/worker/cf/worker.ts@@ -6,8 +6,9 @@// This file is compiled by wrangler, not the site's tsconfig — workers// globals are typed loosely on purpose.import { Container, getContainer } from "@cloudflare/containers";+import { serveMedia, type MediaEnv } from "./media";-type WorkerEnv = {+type WorkerEnv = MediaEnv & {CUT_RENDER_WORKER: unknown;DATABASE_URL: string;R2_ACCOUNT_ID: string;@@ -16,6 +17,8 @@ type WorkerEnv = {CUT_WAKE_SECRET: string;CUT_COPY_EXECUTE_URL: string;CUT_COPY_EXECUTE_SECRET: string;+ /** Hostname the shared-media routes arrive on. */+ CUT_MEDIA_HOST: string;};// Minimal shapes for the queue consumer — this file stays off workers-types@@ -46,8 +49,18 @@ export class CutRenderWorker extends Container<WorkerEnv> {}export default {- async fetch(request: Request, env: WorkerEnv): Promise<Response> {+ async fetch(+ request: Request,+ env: WorkerEnv,+ ctx: { waitUntil(p: Promise<unknown>): void }+ ): Promise<Response> {const url = new URL(request.url);+ // Shared media arrives on its own hostname (see wrangler.jsonc routes) and+ // is the only public traffic this Worker takes. Matching on the host keeps+ // it clear of the container's control endpoints below.+ if (env.CUT_MEDIA_HOST && url.hostname === env.CUT_MEDIA_HOST) {+ return serveMedia(request, env, ctx);+ }if (request.method === "POST" && url.pathname === "/wake") {// Starting the container bills CPU, so the wake is not public: callers// present the shared secret the hosted API holds.diff --git a/site/src/cut/worker/wrangler.jsonc b/site/src/cut/worker/wrangler.jsoncindex d46a45f8..e8212d25 100644--- a/site/src/cut/worker/wrangler.jsonc+++ b/site/src/cut/worker/wrangler.jsonc@@ -25,6 +25,14 @@"durable_objects": {"bindings": [{ "name": "CUT_RENDER_WORKER", "class_name": "CutRenderWorker" }]},+ // Shared media is served from the edge (cf/media.ts) with the bucket kept+ // private: this binding is the only way in. The Cache API is inert on+ // workers.dev, so the route has to be a real hostname on the zone — set+ // CUT_MEDIA_HOST to the same name. Comment both out to leave the feature off;+ // the hosted API then presigns R2 exactly as before.+ "r2_buckets": [{ "binding": "CUT_MEDIA", "bucket_name": "donkey-cut" }],+ "routes": [{ "pattern": "media.donkeycut.com", "custom_domain": true }],+ "vars": { "CUT_MEDIA_HOST": "media.donkeycut.com" },"migrations": [{ "tag": "v1", "new_sqlite_classes": ["CutRenderWorker"] }],// Share-copy jobs drain serially: one message per batch, one batch in// flight, so a burst of copy requests can't stampede R2 or the database.