Open source CapCut alternative.
TypeScript
feat(site): refresh expiring cut media links and retry failed loads
David Lef8ca4a880d39
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.tsindex 272c2085..da44afe0 100644--- a/site/src/cut/hooks/usePlayback.ts+++ b/site/src/cut/hooks/usePlayback.ts@@ -6,6 +6,7 @@ import { isFullRect, overlayAnimStyle, projectFadeSeconds, rectOf, TRANSITION_ZOimport type { AudioClip, ClipAnim, ClipSpan, FrameRect, MediaAsset, TransitionStyle, VideoClip } from "@/cut/lib/types";import { gradeTint, gradeToCssFilter, isNeutralGrade } from "@/cut/lib/colorGrade";import { grainTile, lookCssFilter, lookPost } from "@/cut/lib/looks";+import { reportMediaElementError } from "@/cut/lib/mediaLinks";import { registerSourceSampler } from "@/cut/lib/previewCanvas";/** The alpha/zoom/gain ramps a transition or clip animation puts on one@@ -208,6 +209,9 @@ function makeMediaEl(asset: MediaAsset): MediaEl {if (asset.type === "image") {const img = document.createElement("img");img.crossOrigin = "anonymous";+ // Detached elements never reach the global error listener — report+ // failures explicitly so an expired signed URL re-mints the batch.+ img.addEventListener("error", () => reportMediaElementError(img));img.src = asset.url;return img;}@@ -215,6 +219,7 @@ function makeMediaEl(asset: MediaAsset): MediaEl {v.playsInline = true;v.preload = "auto";v.crossOrigin = "anonymous";+ v.addEventListener("error", () => reportMediaElementError(v));v.src = asset.url;return v;}@@ -1132,8 +1137,11 @@ class Engine {el = undefined;}if (!el) {- el = new Audio(asset.url);- el.preload = "auto";+ const audio = new Audio();+ audio.preload = "auto";+ audio.addEventListener("error", () => reportMediaElementError(audio));+ audio.src = asset.url;+ el = audio;this.audioEls.set(a.id, el);}// Detached audio can carry its video clip's rate; footprint is (out-in)/speed.diff --git a/site/src/cut/lib/backend/cloud.ts b/site/src/cut/lib/backend/cloud.tsindex 564569ea..9332cc3d 100644--- a/site/src/cut/lib/backend/cloud.ts+++ b/site/src/cut/lib/backend/cloud.ts@@ -53,29 +53,49 @@ async function cloudFetch(path: string, init?: RequestInit): Promise<Response> {return res;}+export interface SignedMediaBatch {+ /** fileName -> signed URL. */+ urls: Map<string, string>;+ /** Wall-clock ms when the batch's URLs stop working; null when the mint+ * came back empty or without an expiry. */+ expiresAt: number | null;+}+/** Batch-mint signed R2 GET URLs for a cloud or shared project's media files.- * Returns fileName -> url; anything the mint misses keeps the /media route,- * whose 302 serves the same bytes. Dispatches through the active backend so- * the shared driver's token prefix applies; lazy import because ./index- * imports this module. */+ * Anything the mint misses keeps the /media route, whose 302 serves the same+ * bytes. Network errors and 5xx retry with a short backoff — this runs right+ * after a laptop wakes, when the link may still be coming up. Dispatches+ * through the active backend so the shared driver's token prefix applies;+ * lazy import because ./index imports this module. */export async function fetchSignedMediaUrls(projectId: string,fileNames: string[]-): Promise<Map<string, string>> {- const out = new Map<string, string>();+): Promise<SignedMediaBatch> {+ const out: SignedMediaBatch = { urls: new Map(), expiresAt: null };if (fileNames.length === 0) return out;- try {- const { apiFetch } = await import("./index");- const res = await apiFetch("/api/cut/media/presign-get", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ items: fileNames.map((fileName) => ({ projectId, fileName })) }),- });- if (!res.ok) return out;- const body = (await res.json()) as { urls?: { fileName: string; url: string }[] };- for (const u of body.urls ?? []) out.set(u.fileName, u.url);- } catch {- // Signed URLs are an optimization; the route fallback still streams.+ const { apiFetch } = await import("./index");+ for (let attempt = 0; attempt < 3; attempt++) {+ if (attempt > 0) await new Promise((r) => setTimeout(r, 500 * 2 ** (attempt - 1)));+ try {+ const res = await apiFetch("/api/cut/media/presign-get", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ items: fileNames.map((fileName) => ({ projectId, fileName })) }),+ });+ if (res.status >= 500) continue;+ if (!res.ok) return out; // 4xx: the route fallback still streams+ const body = (await res.json()) as {+ urls?: { fileName: string; url: string }[];+ expiresIn?: number;+ };+ for (const u of body.urls ?? []) out.urls.set(u.fileName, u.url);+ if (out.urls.size > 0 && typeof body.expiresIn === "number") {+ out.expiresAt = Date.now() + body.expiresIn * 1000;+ }+ return out;+ } catch {+ // Network down — retry; signed URLs stay an optimization either way.+ }}return out;}diff --git a/site/src/cut/lib/mediaLinks.ts b/site/src/cut/lib/mediaLinks.tsnew file mode 100644index 00000000..0a8cd491--- /dev/null+++ b/site/src/cut/lib/mediaLinks.ts@@ -0,0 +1,132 @@+"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:+//+// - 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.+//+// 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+const FORCED_GAP_MS = 15_000; // min gap between failure-driven re-mints+const 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 refreshing: Promise<void> | null = null;+let lastForcedAt = 0;++/** 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). */+export function markSignedBatch(projectId: string, expiresAt: number | null) {+ batch = expiresAt === null ? null : { projectId, expiresAt };+}++/** Re-mint the loaded project's signed URLs and swap them into the store.+ * Single-flight; skips while the batch is comfortably fresh unless forced. */+function refreshSignedUrls(force = false): Promise<void> {+ if (refreshing) return refreshing;+ refreshing = (async () => {+ const b = batch;+ if (!b) return;+ if (!force && Date.now() < b.expiresAt - REFRESH_LEAD_MS) return;+ const { useEditor } = await import("./store");+ const s = useEditor.getState();+ if (!s.loaded || s.projectId !== b.projectId) return;+ const minted = await fetchSignedMediaUrls(b.projectId, s.assets.map((a) => a.fileName));+ const st = useEditor.getState();+ if (batch !== b || st.projectId !== b.projectId || !st.loaded) return;+ // Mint down but the current URLs still work (inside the eager-refresh+ // lead, no element failure) — keep them; the next visibility/online+ // event retries.+ if (minted.urls.size === 0 && !force && Date.now() < b.expiresAt) return;+ const urls = new Map<string, string>();+ for (const a of st.assets) {+ 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;+ // A failed mint left every asset on route URLs, which re-sign per request+ // — nothing signed remains to track until the next load.+ else batch = null;+ })().finally(() => {+ refreshing = null;+ });+ return refreshing;+}++const isSignedUrl = (src: string) => src.includes("X-Amz-Signature=");+const isCutApiUrl = (src: string) => src.includes("/api/cut");++const attempts = new WeakMap<Element, { n: number; at: number }>();++function retryElement(el: HTMLImageElement | HTMLMediaElement, src: string, attempt: number) {+ window.setTimeout(() => {+ if (el instanceof HTMLImageElement) {+ if (el.src !== src) return; // repointed since the failure+ el.removeAttribute("src");+ el.src = src;+ } else {+ if ((el.currentSrc || el.src) !== src) return;+ el.load();+ }+ }, ELEMENT_RETRY_BASE_MS * attempt);+}++/** A media element failed to load. Signed URLs re-mint the whole batch (the+ * store swap repoints every consumer); route URLs reload the element itself. */+export 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 (Date.now() - lastForcedAt < FORCED_GAP_MS) return;+ lastForcedAt = Date.now();+ void refreshSignedUrls(true);+ return;+ }+ if (!isCutApiUrl(src)) return;+ const rec = attempts.get(el) ?? { n: 0, at: 0 };+ if (Date.now() - rec.at > ATTEMPT_RESET_MS) rec.n = 0;+ if (rec.n >= ELEMENT_RETRIES) return;+ rec.n += 1;+ rec.at = Date.now();+ attempts.set(el, rec);+ retryElement(el, src, rec.n);+}++if (typeof window !== "undefined") {+ const maybeRefresh = () => {+ if (document.visibilityState !== "visible") return;+ if (batch && Date.now() >= batch.expiresAt - REFRESH_LEAD_MS) void refreshSignedUrls();+ };+ document.addEventListener("visibilitychange", maybeRefresh);+ window.addEventListener("focus", maybeRefresh);+ window.addEventListener("online", maybeRefresh);+ // Error events don't bubble, but the capture phase still passes through+ // window for any element in the document — one listener covers every+ // rendered <video>/<img>. The preview engine's detached decoders report+ // themselves explicitly.+ window.addEventListener(+ "error",+ (e) => {+ const t = e.target;+ if (t instanceof HTMLImageElement || t instanceof HTMLMediaElement) {+ reportMediaElementError(t);+ }+ },+ true+ );+}diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex b6013c97..7499b86f 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -29,6 +29,7 @@ import type { VideoProject } from "./genvideo/types";import { fillSlot } from "./genvideo/fillSlot";import { apiFetch, apiJson, getBackend } from "./backend";import { fetchSignedMediaUrls } from "./backend/cloud";+import { markSignedBatch } from "./mediaLinks";import { cloudTranscribeSpec, type CloudTranscribeSpec } from "./cloudTranscribe";import { trackLocale } from "./subtitles";import { ANIM_STYLE_IDS, emptySubtitles, IMAGE_CLIP_SECONDS, LOOK_IDS, MAX_SUBTITLE_LANES, mediaUrl, migrateLegacyTransitions, SPEED_FLOOR, SPEED_MIN, TRANSITION_MAX } from "./types";@@ -171,6 +172,10 @@ export interface EditorState {setProjectFade: (patch: { fadeIn?: number; fadeOut?: number }) => void;addAsset: (asset: MediaAsset) => void;updateAsset: (id: string, patch: Partial<MediaAsset>) => void;+ /** Swap asset URLs in place (fileName -> url), e.g. after re-minting an+ * expired signed batch. Runtime-only — the stored projection omits url —+ * and allowed in read-only shared views. */+ applyMediaUrls: (urls: Map<string, string>) => void;/** Remove a project asset and any clips/audio that reference it. */removeAsset: (id: string) => void;/** Add a video clip from an asset onto video track 0 — at `start` (sliding@@ -863,10 +868,13 @@ export const useEditor = create<EditorState>((baseSet, get) => {}));// Cloud and shared media ride signed R2 URLs, batch-minted once per// load; the /media route's 302 stays the fallback for anything the- // mint misses.+ // mint misses. mediaLinks re-mints the batch as it nears expiry.if (getBackend().kind !== "local") {const signed = await fetchSignedMediaUrls(id, assets.map((a) => a.fileName));- for (const a of assets) a.url = signed.get(a.fileName) ?? a.url;+ for (const a of assets) a.url = signed.urls.get(a.fileName) ?? a.url;+ markSignedBatch(id, signed.expiresAt);+ } else {+ markSignedBatch(id, null);}// Older docs stored video track 0 packed (array order implied the// position); bake explicit starts in once so every clip is free-placed.@@ -1133,6 +1141,20 @@ export const useEditor = create<EditorState>((baseSet, get) => {}));},+ applyMediaUrls: (urls) => {+ hydrating = true;+ try {+ set((s) => ({+ assets: s.assets.map((a) => {+ const url = urls.get(a.fileName);+ return url && url !== a.url ? { ...a, url } : a;+ }),+ }));+ } finally {+ hydrating = false;+ }+ },+removeAsset: (id) => {const st = get();const gone = st.assets.find((a) => a.id === id);diff --git a/site/src/cut/server/cloud/media.ts b/site/src/cut/server/cloud/media.tsindex 434ab878..468900b6 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 { head, presignGet, presignPut, projectMediaKey, putObject } from "./r2";+import { GET_EXPIRY_SECONDS, head, presignGet, 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 });+ return Response.json({ urls, expiresIn: GET_EXPIRY_SECONDS });} 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.tsindex 0d0d41e8..e13d2d47 100644--- a/site/src/cut/server/cloud/r2.ts+++ b/site/src/cut/server/cloud/r2.ts@@ -14,7 +14,7 @@ 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-const GET_EXPIRY_SECONDS = 24 * 60 * 60; // 24h — hydrated asset URLs live a session+export const GET_EXPIRY_SECONDS = 24 * 60 * 60; // 24h — hydrated asset URLs live a sessionexport class R2NotConfiguredError extends Error {constructor() {diff --git a/site/src/cut/server/cloud/sharedView.ts b/site/src/cut/server/cloud/sharedView.tsindex 0ce282ae..9375d7a4 100644--- a/site/src/cut/server/cloud/sharedView.ts+++ b/site/src/cut/server/cloud/sharedView.ts@@ -7,7 +7,7 @@import type { ProjectDoc, StoredAsset } from "@/cut/lib/types";import { auth } from "@/lib/auth";import { prisma } from "@/lib/prisma";-import { presignGet, projectMediaKey } from "./r2";+import { GET_EXPIRY_SECONDS, presignGet, projectMediaKey } from "./r2";import { normalizeEmails, normalizeFeatures, type ShareFeatures } from "./share";import { caught, decodeFileParam, err, redirect } from "./util";@@ -163,7 +163,7 @@ export const sharedView = {url: await presignGet(projectMediaKey(view.share.userId, i.projectId!, i.fileName!)),})));- return Response.json({ urls });+ return Response.json({ urls, expiresIn: GET_EXPIRY_SECONDS });} catch (e) {return caught(e, "Could not sign the media URLs.");}