|
| 1 | +import type { SourceInfo } from "./thumbnailSourcePool"; |
| 2 | + |
| 3 | +/** A video as the server serves it now: its URL and the ETag of this version of its file. */ |
| 4 | +export interface StoredSource { |
| 5 | + source: string; |
| 6 | + etag: string; |
| 7 | +} |
| 8 | + |
| 9 | +interface StoredFrame { |
| 10 | + blob: Blob; |
| 11 | + decodedAt: number; |
| 12 | +} |
| 13 | + |
| 14 | +const CACHE_PREFIX = "hf-thumbnails:"; |
| 15 | +const INDEX_KEY = "hf-thumbnails-index"; |
| 16 | +const ENTRY_ORIGIN = "https://hf-thumbnail.invalid/"; |
| 17 | +export const STORED_THUMBNAIL_BYTES = 256 * 1024 * 1024; |
| 18 | + |
| 19 | +interface Index { |
| 20 | + etags: Record<string, string>; |
| 21 | + caches: Record<string, { usedAt: number; bytes: number }>; |
| 22 | +} |
| 23 | + |
| 24 | +let index: Index | undefined; |
| 25 | +let saveTimer: ReturnType<typeof setTimeout> | undefined; |
| 26 | +let warned = false; |
| 27 | + |
| 28 | +const available = () => typeof caches !== "undefined" && typeof crypto?.subtle !== "undefined"; |
| 29 | + |
| 30 | +/** Disk is a shortcut, never a reason a thumbnail fails: a broken store says so once and is skipped. */ |
| 31 | +async function quietly<T>(work: () => Promise<T>): Promise<T | undefined> { |
| 32 | + if (!available()) return undefined; |
| 33 | + try { |
| 34 | + return await work(); |
| 35 | + } catch (error) { |
| 36 | + if (!warned) console.warn("[Studio] timeline thumbnails stay in memory:", error); |
| 37 | + warned = true; |
| 38 | + return undefined; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +async function digest(text: string): Promise<string> { |
| 43 | + const bytes = new Uint8Array( |
| 44 | + await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)), |
| 45 | + ); |
| 46 | + return Array.from(bytes.subarray(0, 12), (byte) => byte.toString(16).padStart(2, "0")).join(""); |
| 47 | +} |
| 48 | + |
| 49 | +const cacheNameOf = async ({ source, etag }: StoredSource) => |
| 50 | + `${CACHE_PREFIX}${await digest(source)}:${await digest(etag)}`; |
| 51 | + |
| 52 | +function loadIndex(): Index { |
| 53 | + if (index) return index; |
| 54 | + try { |
| 55 | + const saved = JSON.parse(localStorage.getItem(INDEX_KEY) ?? "null") as Index | null; |
| 56 | + if (saved?.etags && saved.caches) index = saved; |
| 57 | + } catch { |
| 58 | + // expected: no storage (a private window) or a value this version can't read starts an empty index |
| 59 | + } |
| 60 | + return (index ??= { etags: {}, caches: {} }); |
| 61 | +} |
| 62 | + |
| 63 | +function saveIndexSoon(): void { |
| 64 | + saveTimer ??= setTimeout(() => { |
| 65 | + saveTimer = undefined; |
| 66 | + try { |
| 67 | + localStorage.setItem(INDEX_KEY, JSON.stringify(loadIndex())); |
| 68 | + } catch { |
| 69 | + // expected: storage refused; the caches still hold the frames, only their order of use is lost |
| 70 | + } |
| 71 | + }, 1000); |
| 72 | +} |
| 73 | + |
| 74 | +function used(name: string, addedBytes = 0): void { |
| 75 | + const caches = loadIndex().caches; |
| 76 | + caches[name] = { usedAt: Date.now(), bytes: (caches[name]?.bytes ?? 0) + addedBytes }; |
| 77 | + saveIndexSoon(); |
| 78 | +} |
| 79 | + |
| 80 | +/** The version stored for `source`, when one conditional one-byte read says the server still has it (304). */ |
| 81 | +export const storedVersion = (source: string) => |
| 82 | + quietly(async (): Promise<StoredSource | undefined> => { |
| 83 | + const etag = loadIndex().etags[await digest(source)]; |
| 84 | + if (!etag) return undefined; |
| 85 | + // oxlint-disable-next-line no-restricted-globals -- one validation read, on the media's own route like mediabunny's |
| 86 | + const response = await fetch(source, { |
| 87 | + headers: { Range: "bytes=0-0", "If-None-Match": etag }, |
| 88 | + }); |
| 89 | + await response.body?.cancel(); |
| 90 | + return response.status === 304 ? { source, etag } : undefined; |
| 91 | + }); |
| 92 | + |
| 93 | +/** Records the version the server now has, dropping what was stored for the source's earlier versions. */ |
| 94 | +export const rememberVersion = (stored: StoredSource) => |
| 95 | + quietly(async () => { |
| 96 | + const key = await digest(stored.source); |
| 97 | + const saved = loadIndex(); |
| 98 | + if (saved.etags[key] === stored.etag) return; |
| 99 | + saved.etags[key] = stored.etag; |
| 100 | + saveIndexSoon(); |
| 101 | + const keep = await cacheNameOf(stored); |
| 102 | + for (const name of await caches.keys()) { |
| 103 | + if (!name.startsWith(`${CACHE_PREFIX}${key}:`) || name === keep) continue; |
| 104 | + await caches.delete(name); |
| 105 | + delete saved.caches[name]; |
| 106 | + } |
| 107 | + }); |
| 108 | + |
| 109 | +async function entry(stored: StoredSource, path: string) { |
| 110 | + const name = await cacheNameOf(stored); |
| 111 | + return { name, cache: await caches.open(name), url: `${ENTRY_ORIGIN}${path}` }; |
| 112 | +} |
| 113 | + |
| 114 | +/** A read opens nothing: opening a cache creates it, and an empty one for a gone version would never be dropped. */ |
| 115 | +async function storedEntry(stored: StoredSource, path: string) { |
| 116 | + const name = await cacheNameOf(stored); |
| 117 | + return (await caches.has(name)) ? entry(stored, path) : undefined; |
| 118 | +} |
| 119 | + |
| 120 | +export const readStoredInfo = (stored: StoredSource) => |
| 121 | + quietly(async (): Promise<SourceInfo | undefined> => { |
| 122 | + const found = await storedEntry(stored, "info"); |
| 123 | + if (!found) return undefined; |
| 124 | + const { name, cache, url } = found; |
| 125 | + const info = (await (await cache.match(url))?.json()) as SourceInfo | undefined; |
| 126 | + if (!(info && info.aspect > 0)) return undefined; |
| 127 | + used(name); |
| 128 | + return info; |
| 129 | + }); |
| 130 | + |
| 131 | +export const storeInfo = (stored: StoredSource, info: SourceInfo) => |
| 132 | + quietly(async () => { |
| 133 | + const { name, cache, url } = await entry(stored, "info"); |
| 134 | + await cache.put(url, new Response(JSON.stringify(info))); |
| 135 | + used(name); |
| 136 | + }); |
| 137 | + |
| 138 | +/** `frame` names one picture of the source: its fit, size and the time it was asked for. */ |
| 139 | +export const readStoredFrame = (stored: StoredSource, frame: string) => |
| 140 | + quietly(async (): Promise<StoredFrame | undefined> => { |
| 141 | + const found = await storedEntry(stored, `frame?${encodeURIComponent(frame)}`); |
| 142 | + if (!found) return undefined; |
| 143 | + const { name, cache, url } = found; |
| 144 | + const response = await cache.match(url); |
| 145 | + const decodedAt = Number(response?.headers.get("x-decoded-at")); |
| 146 | + if (!response || !Number.isFinite(decodedAt)) return undefined; |
| 147 | + used(name); |
| 148 | + return { blob: await response.blob(), decodedAt }; |
| 149 | + }); |
| 150 | + |
| 151 | +export const storeFrame = (stored: StoredSource, frame: string, decodedAt: number, blob: Blob) => |
| 152 | + quietly(async () => { |
| 153 | + const { name, cache, url } = await entry(stored, `frame?${encodeURIComponent(frame)}`); |
| 154 | + const headers = { "content-type": blob.type, "x-decoded-at": String(decodedAt) }; |
| 155 | + await cache.put(url, new Response(blob, { headers })); |
| 156 | + used(name, blob.size); |
| 157 | + await dropLeastUsed(STORED_THUMBNAIL_BYTES); |
| 158 | + }); |
| 159 | + |
| 160 | +/** Whole sources go, least recently used first, until what is stored fits `budgetBytes`. */ |
| 161 | +async function dropLeastUsed(budgetBytes: number): Promise<void> { |
| 162 | + const saved = loadIndex(); |
| 163 | + let total = Object.values(saved.caches).reduce((sum, { bytes }) => sum + bytes, 0); |
| 164 | + const oldestFirst = Object.entries(saved.caches).sort(([, a], [, b]) => a.usedAt - b.usedAt); |
| 165 | + for (const [name, { bytes }] of oldestFirst) { |
| 166 | + if (total <= budgetBytes) break; |
| 167 | + await caches.delete(name); |
| 168 | + delete saved.caches[name]; |
| 169 | + total -= bytes; |
| 170 | + } |
| 171 | + saveIndexSoon(); |
| 172 | +} |
| 173 | + |
| 174 | +/** Tests only: forget the in-memory index and any pending save. */ |
| 175 | +export function resetStoredThumbnailsForTests(): void { |
| 176 | + clearTimeout(saveTimer); |
| 177 | + saveTimer = undefined; |
| 178 | + index = undefined; |
| 179 | + warned = false; |
| 180 | +} |
0 commit comments