// --------------------------------------------------------------------------- // POST ITEMS FETCHED AHEAD (operator, 4 Nov: "The rapid sections on play the // cut don't load fast enough such that most of it is cut out. Can we maybe // preload?"). A post item's player (PostItemPlayer.tsx) is mounted only while // its item is on screen, and everything it draws was asked for then: the card's // page (and its faces and avatars), the narration take, the attachments. A // `pace: fast` burst is items of 1-4 s back to back, so each was mostly over // before it had loaded. // // So Play hands this the items AHEAD of the playhead (PlayCut.tsx: ~20 s of // them, more when they are short) and each one's bytes are fetched here, the // nearest first, a few at a time: // // - the card's PAGE as text, its own requests (the cut's faces, the avatars, // a parent's screenshot: the route's `file=` / `font=` URLs) fetched too and // written into it as blob URLs -- the player draws it as `srcdoc`, so the // frame needs nothing from the network; // - every FILE (the take, the attachments, a video's words) as a Blob, handed // to the element as a blob URL (in memory: a seek never waits on a range). // // The player asks `docOf` / `urlOf` once per element, when it mounts (a src // never changes under a playing element); anything not here yet is fetched by // the element itself, as before. What is behind the playhead is let go (its // blob URLs revoked), and a file over MAX_FILE, or past the budget, is left to // the element. `itemState` is what Play's clock asks before it crosses into an // item (engine.ts `gate`): still fetching, it holds on the item before. // --------------------------------------------------------------------------- /** What one post item needs: its card pages (read, media, the join's) and its files. */ export type PostAssets = { id: string; docs: string[]; files: string[] }; export type PreloadState = "ready" | "loading" | "partial" | "none"; type Asset = { url: string; kind: "doc" | "file"; state: "queued" | "loading" | "ready" | "failed" | "skipped"; /** The doc's html (its requests in it as blob URLs), or the file's blob URL. */ out: string | null; bytes: number; users: Set; prio: number; ctrl: AbortController | null; /** A doc's own requests (files), settled before the doc is. */ subs: string[]; settled: Promise; settle: () => void; }; /** A file bigger than this is left to its element (a long screen recording): not held in memory. */ const MAX_FILE = 64 * 1024 * 1024; /** Everything held at once. */ const BUDGET = 384 * 1024 * 1024; /** Requests in flight at once: the rest of the page (the engine's clips, the chrome) keeps the other connections. */ const CONCURRENCY = 4; /** The card page's own requests: the route's files and faces (post-item.mjs: avatars, a parent's shot, @font-face). */ const SUB_RE = /\/api\/report\/post-item\?[^"'()\s<>\\]+/g; class PostPreloader { private assets = new Map(); private items = new Map(); private active = 0; private bytes = 0; /** For a console and the e2e (play-preload.spec.ts): what was fetched ahead, and how it went. */ stats = { asked: 0, ready: 0, failed: 0, skipped: 0, released: 0 }; /** * The items wanted now, nearest first; everything else is let go. `keep`: * items whose bytes are kept but never fetched now (the one on screen, which * its player is already loading, and the one before it, whose last frame a * join opens on). */ want(list: PostAssets[], keep: PostAssets[] = []) { const ids = new Set([...list, ...keep].map((x) => x.id)); for (const a of this.assets.values()) a.prio = Infinity; for (const it of keep) { this.items.set(it.id, it); for (const url of [...it.docs, ...it.files]) { const a = this.assets.get(url); if (a) { a.users.add(it.id); a.prio = -1; for (const s of a.subs) this.assets.get(s)?.users.add(it.id); } } } list.forEach((it, k) => { this.items.set(it.id, it); for (const url of it.docs) this.ask(url, "doc", it.id, k); for (const url of it.files) this.ask(url, "file", it.id, k); }); // Let go after: a file the items wanted now share with one let go (a repeated attachment) is kept, not fetched again. for (const id of [...this.items.keys()]) if (!ids.has(id)) this.release(id); this.pump(); } /** The card page at `url`, ready to draw as srcdoc, or null. */ docOf(url: string): string | null { const a = this.assets.get(url); return a?.kind === "doc" && a.state === "ready" ? a.out : null; } /** The file at `url` as a blob URL when it is here, else `url` itself. */ urlOf(url: string): string { const a = this.assets.get(url); return a?.kind === "file" && a.state === "ready" && a.out ? a.out : url; } /** An item's bytes: all here, still coming, here but for some (failed, too big), or not asked for. */ itemState(id: string): PreloadState { const it = this.items.get(id); if (!it) return "none"; let partial = false; const look = (url: string): boolean => { const a = this.assets.get(url); if (!a) { partial = true; return true; } if (a.state === "queued" || a.state === "loading") return false; if (a.state !== "ready") partial = true; return a.subs.every(look); }; for (const url of [...it.docs, ...it.files]) if (!look(url)) return "loading"; return partial ? "partial" : "ready"; } clear() { for (const id of [...this.items.keys()]) this.release(id); } private ask(url: string, kind: Asset["kind"], user: string, prio: number) { let a = this.assets.get(url); if (!a) { let settle = () => {}; const settled = new Promise((r) => (settle = r)); a = { url, kind, state: "queued", out: null, bytes: 0, users: new Set(), prio, ctrl: null, subs: [], settled, settle }; this.assets.set(url, a); this.stats.asked += 1; } a.users.add(user); a.prio = Math.min(a.prio, prio); for (const s of a.subs) { const sub = this.assets.get(s); if (sub) { sub.users.add(user); sub.prio = Math.min(sub.prio, prio); } } } private release(id: string) { this.items.delete(id); for (const a of [...this.assets.values()]) { if (!a.users.delete(id) || a.users.size) continue; a.ctrl?.abort(); if (a.kind === "file" && a.out) URL.revokeObjectURL(a.out); this.bytes -= a.bytes; this.assets.delete(a.url); if (a.state === "queued" || a.state === "loading") a.settle(); this.stats.released += 1; } } private pump() { while (this.active < CONCURRENCY) { let next: Asset | null = null; for (const a of this.assets.values()) if (a.state === "queued" && a.prio !== Infinity && (!next || a.prio < next.prio)) next = a; if (!next) return; next.state = "loading"; this.active += 1; const a = next; void (a.kind === "doc" ? this.loadDoc(a) : this.loadFile(a)).finally(() => { this.active -= 1; this.pump(); }); } } private done(a: Asset, state: "ready" | "failed" | "skipped") { if (this.assets.get(a.url) !== a) return; a.state = state; this.stats[state] += 1; a.settle(); } private async loadFile(a: Asset) { a.ctrl = new AbortController(); try { const r = await fetch(a.url, { signal: a.ctrl.signal }); const len = Number(r.headers.get("content-length") ?? 0); if (!r.ok) throw new Error(`HTTP ${r.status}`); if (len > MAX_FILE || this.bytes + len > BUDGET) { a.ctrl.abort(); this.done(a, "skipped"); return; } const blob = await r.blob(); if (this.assets.get(a.url) !== a) return; a.bytes = blob.size; this.bytes += blob.size; a.out = URL.createObjectURL(blob); this.done(a, "ready"); } catch { this.done(a, "failed"); } finally { a.ctrl = null; } } private async loadDoc(a: Asset) { a.ctrl = new AbortController(); let html: string; try { const r = await fetch(a.url, { signal: a.ctrl.signal }); if (!r.ok) throw new Error(`HTTP ${r.status}`); html = await r.text(); } catch { a.ctrl = null; this.done(a, "failed"); return; } a.ctrl = null; if (this.assets.get(a.url) !== a) return; // Its own requests, as written in it (an attribute's `&`, a style's raw `&`), each fetched as a file. const found = [...new Set(html.match(SUB_RE) ?? [])].filter((m) => /[?&](amp;)?(file|font)=/.test(m)); const real = new Map(found.map((m) => [m, m.replace(/&/g, "&")])); a.subs = [...new Set(real.values())]; for (const s of a.subs) for (const u of a.users) this.ask(s, "file", u, a.prio); // The doc's slot is free while its requests come (they queue at its priority, ahead of farther items). void Promise.all(a.subs.map((s) => this.assets.get(s)?.settled)).then(() => { if (this.assets.get(a.url) !== a) return; let out = html; for (const [m, u] of real) { const b = this.urlOf(u); if (b !== u) out = out.split(m).join(b); } a.out = out; this.done(a, "ready"); }); } } /** One for the page: Play fills it, and every post item's player reads it (the bench's, which nothing fills, too). */ export const postPreload = new PostPreloader();