feat(media): shared web helpers for byte routes, polling and studio context

This commit is contained in:
Claude 2026-10-03 19:10:10 +00:00
parent 884d8903ca
commit 159fafdb55
No known key found for this signature in database
3 changed files with 320 additions and 0 deletions

View File

@ -0,0 +1,218 @@
import { useEffect, useState } from "react";
import { selectedSpaceId, withSpaceHeaders } from "./rpc";
/*
* Media byte routes (thumbnails, proxies, render files, bundles, upload chunks).
* They need the session cookie and the space header, which an `<img src>` or
* `<video src>` cannot send, so bytes are fetched here and handed to elements
* as object URLs. Thumbnails stay cached after release; large files do not.
*/
export type MediaAssetFile = "thumb" | "proxy";
export function mediaAssetPath(assetId: string, file: MediaAssetFile): string {
return `/api/media/assets/${encodeURIComponent(assetId)}/${file}`;
}
export function mediaRenderFilePath(
renderId: string,
fileName: string,
options: { download?: boolean } = {},
): string {
const base = `/api/media/renders/${encodeURIComponent(renderId)}/files/${encodeURIComponent(fileName)}`;
return options.download ? `${base}?download=1` : base;
}
export function mediaBundlePath(publicationId: string): string {
return `/api/media/bundles/${encodeURIComponent(publicationId)}`;
}
export function mediaUploadChunkPath(uploadId: string, index: number): string {
return `/api/media/uploads/${encodeURIComponent(uploadId)}/chunks/${index}`;
}
export class MediaFetchError extends Error {
constructor(readonly status: number) {
super(`Media request failed (${status})`);
this.name = "MediaFetchError";
}
}
/** Fetch a media byte route with the session cookie and the selected space. */
export async function fetchMedia(path: string, init: RequestInit = {}): Promise<Response> {
const response = await fetch(path, {
...init,
credentials: "include",
headers: withSpaceHeaders(init.headers),
});
if (!response.ok) throw new MediaFetchError(response.status);
return response;
}
/** Save a media file through the browser's download flow. */
export async function downloadMedia(path: string, fileName: string): Promise<void> {
const blob = await (await fetchMedia(path)).blob();
const url = URL.createObjectURL(blob);
try {
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = fileName;
anchor.click();
} finally {
setTimeout(() => URL.revokeObjectURL(url), 30_000);
}
}
type Entry = {
promise: Promise<string>;
url: string | null;
refs: number;
/** Keep the object URL after the last release (small files such as thumbnails). */
keep: boolean;
controller: AbortController;
};
/** Idle thumbnails kept around for scrolling back; each one is a few KB. */
export const MEDIA_IDLE_CACHE_LIMIT = 400;
export interface MediaObjectUrlCache {
acquire(
path: string,
options?: { keep?: boolean },
): { promise: Promise<string>; release: () => void };
/** Number of entries, including idle ones (for tests). */
size(): number;
clear(): void;
}
export function createMediaObjectUrlCache(deps: {
load: (path: string, signal: AbortSignal) => Promise<Blob>;
createUrl: (blob: Blob) => string;
revokeUrl: (url: string) => void;
spaceId: () => string | null;
idleLimit?: number;
}): MediaObjectUrlCache {
const entries = new Map<string, Entry>();
const idleLimit = deps.idleLimit ?? MEDIA_IDLE_CACHE_LIMIT;
const drop = (key: string, entry: Entry) => {
entries.delete(key);
entry.controller.abort();
if (entry.url) deps.revokeUrl(entry.url);
};
const trim = () => {
let idle = 0;
for (const entry of entries.values()) if (entry.refs === 0) idle += 1;
for (const [key, entry] of entries) {
if (idle <= idleLimit) break;
if (entry.refs > 0) continue;
drop(key, entry);
idle -= 1;
}
};
return {
acquire(path, options = {}) {
const key = `${deps.spaceId() ?? ""}|${path}`;
let entry = entries.get(key);
if (entry) {
// Re-insert so the map order stays least recently used first.
entries.delete(key);
entries.set(key, entry);
} else {
const controller = new AbortController();
const created: Entry = {
url: null,
refs: 0,
keep: options.keep ?? false,
controller,
promise: Promise.resolve(""),
};
created.promise = deps.load(path, controller.signal).then(
(blob) => {
const url = deps.createUrl(blob);
if (entries.get(key) !== created) {
deps.revokeUrl(url);
throw new DOMException("Released", "AbortError");
}
created.url = url;
return url;
},
(error: unknown) => {
if (entries.get(key) === created) entries.delete(key);
throw error;
},
);
// Callers that went away never observe the rejection.
created.promise.catch(() => undefined);
entries.set(key, created);
entry = created;
}
const held = entry;
held.refs += 1;
let released = false;
return {
promise: held.promise,
release: () => {
if (released) return;
released = true;
held.refs -= 1;
if (held.refs > 0 || entries.get(key) !== held) return;
if (held.keep && held.url) trim();
else drop(key, held);
},
};
},
size: () => entries.size,
clear: () => {
for (const [key, entry] of entries) drop(key, entry);
},
};
}
const sharedCache = createMediaObjectUrlCache({
load: async (path, signal) => (await fetchMedia(path, { signal })).blob(),
createUrl: (blob) => URL.createObjectURL(blob),
revokeUrl: (url) => URL.revokeObjectURL(url),
spaceId: selectedSpaceId,
});
export type MediaObjectUrlState =
| { status: "idle" | "loading"; url: null }
| { status: "ready"; url: string }
| { status: "missing"; url: null };
/**
* Object URL for a media byte route, or null while loading, when `path` is null,
* or when the file does not exist (yet). `keep` caches the bytes after unmount.
*/
export function useMediaObjectUrl(
path: string | null,
options: { keep?: boolean } = {},
): MediaObjectUrlState {
const keep = options.keep ?? false;
const [state, setState] = useState<MediaObjectUrlState>({ status: "idle", url: null });
useEffect(() => {
if (!path) {
setState({ status: "idle", url: null });
return;
}
let active = true;
setState({ status: "loading", url: null });
const handle = sharedCache.acquire(path, { keep });
handle.promise.then(
(url) => {
if (active) setState({ status: "ready", url });
},
() => {
if (active) setState({ status: "missing", url: null });
},
);
return () => {
active = false;
handle.release();
};
}, [path, keep]);
return state;
}

View File

@ -0,0 +1,51 @@
import { useEffect, useRef } from "react";
/** Media has no realtime subscription: clients poll while work runs, then stop. */
export const MEDIA_POLL_MS = 2000;
/**
* Call `tick` every `intervalMs` while `active`. Ticks never overlap: the next
* one is scheduled after the previous settles. Hidden tabs skip ticks.
*/
export function usePolling(
tick: () => unknown,
active: boolean,
intervalMs: number = MEDIA_POLL_MS,
): void {
const latest = useRef(tick);
latest.current = tick;
useEffect(() => {
if (!active) return;
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const schedule = () => {
if (stopped) return;
timer = setTimeout(run, intervalMs);
};
const run = async () => {
if (stopped) return;
if (typeof document !== "undefined" && document.hidden) {
schedule();
return;
}
try {
await latest.current();
} catch {
// The caller renders its own error state; polling continues.
}
schedule();
};
schedule();
return () => {
stopped = true;
if (timer) clearTimeout(timer);
};
}, [active, intervalMs]);
}
/** Render states that still change on the server. */
export const MEDIA_RENDER_ACTIVE_STATES = ["queued", "rendering", "gating"] as const;
export function isRenderActive(status: string): boolean {
return (MEDIA_RENDER_ACTIVE_STATES as readonly string[]).includes(status);
}

View File

@ -0,0 +1,51 @@
import type { MediaCapabilities } from "@rakazo/contracts";
import { createContext, useContext, useEffect, useState } from "react";
import { rpc } from "./rpc";
/** What every Media Studio view may read about the deployment. */
export interface MediaStudioEnv {
capabilities: MediaCapabilities | null;
/** Folder sources live on the host, so only the deployment owner links them. */
canLinkFolder: boolean;
}
export const MediaStudioContext = createContext<MediaStudioEnv>({
capabilities: null,
canLinkFolder: false,
});
export function useMediaStudio(): MediaStudioEnv {
return useContext(MediaStudioContext);
}
/** Load media capabilities once; null until known, and on failure. */
export function useMediaCapabilities(enabled = true): MediaCapabilities | null {
const [capabilities, setCapabilities] = useState<MediaCapabilities | null>(null);
useEffect(() => {
if (!enabled) return;
let active = true;
rpc.media
.capabilities({})
.then((value) => {
if (active) setCapabilities(value);
})
.catch(() => undefined);
return () => {
active = false;
};
}, [enabled]);
return capabilities;
}
/** Media Studio entry points stay hidden unless the deployment configured it. */
export function useMediaStudioAvailable(enabled = true): boolean {
return useMediaCapabilities(enabled)?.configured === true;
}
export function rpcErrorMessage(error: unknown, fallback: string): string {
if (error && typeof error === "object" && "message" in error) {
const message = String((error as { message: unknown }).message);
if (message && !/^(Internal|Bad Request|Precondition)/i.test(message)) return message;
}
return fallback;
}