Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(recorder-core): add recording spool with idle recovery guard

Richie McIlroycb207a514ce2
diff --git a/packages/recorder-core/__tests__/recording-spool.test.ts b/packages/recorder-core/__tests__/recording-spool.test.ts
new file mode 100644
index 000000000..ac0897b51
--- /dev/null
+++ b/packages/recorder-core/__tests__/recording-spool.test.ts
@@ -0,0 +1,529 @@
+import {
+ deleteRecoveredRecordingSpool,
+ RecordingSpool,
+ type RecordingSpoolBackend,
+ RecordingSpoolBackpressureError,
+ type RecordingSpoolSessionRecord,
+ recoverOrphanedRecordingSpools,
+} from "@cap/recorder-core/recording-spool";
+import { describe, expect, it } from "vitest";
+
+class MemoryRecordingSpoolBackend implements RecordingSpoolBackend {
+ private readonly sessions = new Map<string, RecordingSpoolSessionRecord>();
+ private readonly chunks = new Map<
+ string,
+ Array<{ index: number; blob: Blob }>
+ >();
+ private readonly failureAtIndex: number | null;
+ private readonly readFailureSessionId: string | null;
+
+ constructor(options?: {
+ failureAtIndex?: number | null;
+ readFailureSessionId?: string | null;
+ }) {
+ this.failureAtIndex = options?.failureAtIndex ?? null;
+ this.readFailureSessionId = options?.readFailureSessionId ?? null;
+ }
+
+ async initialize() {}
+
+ async createSession(session: RecordingSpoolSessionRecord) {
+ this.sessions.set(session.sessionId, session);
+ }
+
+ async appendChunk(
+ session: RecordingSpoolSessionRecord,
+ index: number,
+ chunk: Blob,
+ ) {
+ if (this.failureAtIndex === index) {
+ throw new Error(`Failed to persist chunk ${index}`);
+ }
+
+ this.sessions.set(session.sessionId, session);
+ const existingChunks = this.chunks.get(session.sessionId) ?? [];
+ existingChunks.push({ index, blob: chunk });
+ this.chunks.set(session.sessionId, existingChunks);
+ }
+
+ async readChunks(sessionId: string) {
+ if (this.readFailureSessionId === sessionId) {
+ throw new Error(`Failed to read chunks for ${sessionId}`);
+ }
+
+ return [...(this.chunks.get(sessionId) ?? [])]
+ .sort((left, right) => left.index - right.index)
+ .map((chunk) => chunk.blob);
+ }
+
+ async listSessions() {
+ return [...this.sessions.values()];
+ }
+
+ async deleteSession(sessionId: string) {
+ this.sessions.delete(sessionId);
+ this.chunks.delete(sessionId);
+ }
+
+ getSessionCount() {
+ return this.sessions.size;
+ }
+
+ getChunkCount(sessionId: string) {
+ return this.chunks.get(sessionId)?.length ?? 0;
+ }
+}
+
+const blobToText = async (blob: Blob) =>
+ new TextDecoder().decode(await blob.arrayBuffer());
+
+class DelayedRecordingSpoolBackend implements RecordingSpoolBackend {
+ private readonly sessions = new Map<string, RecordingSpoolSessionRecord>();
+ private readonly chunks = new Map<
+ string,
+ Array<{ index: number; blob: Blob }>
+ >();
+ private resolveAppend: (() => void) | null = null;
+ private pendingAppend: Promise<void> | null = null;
+
+ async initialize() {}
+
+ async createSession(session: RecordingSpoolSessionRecord) {
+ this.sessions.set(session.sessionId, session);
+ }
+
+ async appendChunk(
+ session: RecordingSpoolSessionRecord,
+ index: number,
+ chunk: Blob,
+ ) {
+ this.sessions.set(session.sessionId, session);
+
+ if (!this.pendingAppend) {
+ this.pendingAppend = new Promise<void>((resolve) => {
+ this.resolveAppend = resolve;
+ });
+ }
+
+ await this.pendingAppend;
+
+ const existingChunks = this.chunks.get(session.sessionId) ?? [];
+ existingChunks.push({ index, blob: chunk });
+ this.chunks.set(session.sessionId, existingChunks);
+ }
+
+ async readChunks(sessionId: string) {
+ return [...(this.chunks.get(sessionId) ?? [])]
+ .sort((left, right) => left.index - right.index)
+ .map((entry) => entry.blob);
+ }
+
+ async listSessions() {
+ return [...this.sessions.values()];
+ }
+
+ async deleteSession(sessionId: string) {
+ this.sessions.delete(sessionId);
+ this.chunks.delete(sessionId);
+ }
+
+ releaseAppend() {
+ this.resolveAppend?.();
+ this.resolveAppend = null;
+ this.pendingAppend = null;
+ }
+}
+
+describe("RecordingSpool", () => {
+ it("persists chunks in order and rebuilds the recording blob", async () => {
+ const backend = new MemoryRecordingSpoolBackend();
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm;codecs=vp9,opus",
+ sessionId: "session-1",
+ },
+ backend,
+ );
+
+ await spool.appendChunk(new Blob(["first-"], { type: "video/webm" }));
+ await spool.appendChunk(new Blob(["second"], { type: "video/webm" }));
+
+ expect(spool.chunkCount).toBe(2);
+ expect(spool.totalBytes).toBe(12);
+
+ const blob = await spool.toBlob();
+
+ expect(blob).not.toBeNull();
+ expect(blob?.type).toBe("video/webm;codecs=vp9,opus");
+ expect(await blobToText(blob as Blob)).toBe("first-second");
+ });
+
+ it("keeps queued chunk indexes unique when appends overlap", async () => {
+ const backend = new MemoryRecordingSpoolBackend();
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-overlap",
+ },
+ backend,
+ );
+
+ await Promise.all([
+ spool.appendChunk(new Blob(["first-"], { type: "video/webm" })),
+ spool.appendChunk(new Blob(["second-"], { type: "video/webm" })),
+ spool.appendChunk(new Blob(["third"], { type: "video/webm" })),
+ ]);
+
+ const blob = await spool.toBlob();
+
+ expect(await blobToText(blob as Blob)).toBe("first-second-third");
+ expect(spool.chunkCount).toBe(3);
+ expect(backend.getChunkCount("session-overlap")).toBe(3);
+ });
+
+ it("cleans up persisted state when disposed", async () => {
+ const backend = new MemoryRecordingSpoolBackend();
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-2",
+ },
+ backend,
+ );
+
+ await spool.appendChunk(new Blob(["chunk"], { type: "video/webm" }));
+ expect(backend.getSessionCount()).toBe(1);
+ expect(backend.getChunkCount("session-2")).toBe(1);
+
+ await spool.dispose();
+
+ expect(backend.getSessionCount()).toBe(0);
+ expect(backend.getChunkCount("session-2")).toBe(0);
+ });
+
+ it("fails fast when the pending spool backlog grows beyond its limit", async () => {
+ const backend = new DelayedRecordingSpoolBackend();
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-backpressure",
+ maxPendingChunkBytes: 6,
+ },
+ backend,
+ );
+
+ const firstWrite = spool.appendChunk(
+ new Blob(["1234"], { type: "video/webm" }),
+ );
+
+ await expect(
+ spool.appendChunk(new Blob(["5678"], { type: "video/webm" })),
+ ).rejects.toBeInstanceOf(RecordingSpoolBackpressureError);
+
+ backend.releaseAppend();
+ await Promise.allSettled([firstWrite]);
+
+ const recoveredBlob = await spool.recoverBlob();
+
+ expect(await blobToText(recoveredBlob as Blob)).toBe("12345678");
+ });
+
+ it("surfaces storage write failures", async () => {
+ const backend = new MemoryRecordingSpoolBackend({ failureAtIndex: 1 });
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-3",
+ },
+ backend,
+ );
+
+ await spool.appendChunk(new Blob(["chunk-1"], { type: "video/webm" }));
+ await expect(
+ spool.appendChunk(new Blob(["chunk-2"], { type: "video/webm" })),
+ ).rejects.toThrow("Failed to persist chunk 1");
+ await expect(spool.toBlob()).rejects.toThrow("Failed to persist chunk 1");
+ });
+
+ it("recovers the persisted data and failed in-memory chunk after a write failure", async () => {
+ const backend = new MemoryRecordingSpoolBackend({ failureAtIndex: 1 });
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-4",
+ },
+ backend,
+ );
+
+ await spool.appendChunk(new Blob(["chunk-1"], { type: "video/webm" }));
+ await expect(
+ spool.appendChunk(new Blob(["chunk-2"], { type: "video/webm" })),
+ ).rejects.toThrow("Failed to persist chunk 1");
+
+ const blob = await spool.recoverBlob();
+
+ expect(await blobToText(blob as Blob)).toBe("chunk-1chunk-2");
+ });
+
+ it("keeps queued in-memory chunks available after a write failure", async () => {
+ const backend = new MemoryRecordingSpoolBackend({ failureAtIndex: 1 });
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-5",
+ },
+ backend,
+ );
+
+ const firstWrite = spool.appendChunk(
+ new Blob(["chunk-1|"], { type: "video/webm" }),
+ );
+ const secondWrite = spool.appendChunk(
+ new Blob(["chunk-2|"], { type: "video/webm" }),
+ );
+ const thirdWrite = spool.appendChunk(
+ new Blob(["chunk-3"], { type: "video/webm" }),
+ );
+
+ await firstWrite;
+ await expect(secondWrite).rejects.toThrow("Failed to persist chunk 1");
+ await expect(thirdWrite).rejects.toThrow("Failed to persist chunk 1");
+
+ const blob = await spool.recoverBlob();
+
+ expect(await blobToText(blob as Blob)).toBe("chunk-1|chunk-2|chunk-3");
+ });
+
+ it("cleans up persisted state after a write failure", async () => {
+ const backend = new MemoryRecordingSpoolBackend({ failureAtIndex: 1 });
+ const spool = await RecordingSpool.create(
+ {
+ mimeType: "video/webm",
+ sessionId: "session-cleanup",
+ },
+ backend,
+ );
+
+ await spool.appendChunk(new Blob(["chunk-1"], { type: "video/webm" }));
+ await expect(
+ spool.appendChunk(new Blob(["chunk-2"], { type: "video/webm" })),
+ ).rejects.toThrow("Failed to persist chunk 1");
+
+ await spool.dispose();
+
+ expect(backend.getSessionCount()).toBe(0);
+ expect(backend.getChunkCount("session-cleanup")).toBe(0);
+ });
+
+ it("recovers orphaned spools in newest-first order without deleting them", async () => {
+ const backend = new MemoryRecordingSpoolBackend();
+ await backend.initialize();
+ await backend.createSession({
+ sessionId: "older",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 100,
+ updatedAt: 200,
+ });
+ await backend.appendChunk(
+ {
+ sessionId: "older",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 100,
+ updatedAt: 200,
+ },
+ 0,
+ new Blob(["older"], { type: "video/webm" }),
+ );
+ await backend.createSession({
+ sessionId: "newer",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 300,
+ updatedAt: 400,
+ });
+ await backend.appendChunk(
+ {
+ sessionId: "newer",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 300,
+ updatedAt: 400,
+ },
+ 0,
+ new Blob(["newer"], { type: "video/webm" }),
+ );
+
+ const recovered = await recoverOrphanedRecordingSpools(backend);
+ const [newer, older] = recovered;
+
+ expect(recovered.map((item) => item.sessionId)).toEqual(["newer", "older"]);
+ if (!newer || !older) {
+ throw new Error("Expected recovered recordings");
+ }
+ expect(await blobToText(newer.blob)).toBe("newer");
+ expect(await blobToText(older.blob)).toBe("older");
+ expect(backend.getSessionCount()).toBe(2);
+ expect(backend.getChunkCount("newer")).toBe(1);
+ expect(backend.getChunkCount("older")).toBe(1);
+ });
+
+ it("skips recently updated spools so live cross-tab recordings are not offered as recovered", async () => {
+ const backend = new MemoryRecordingSpoolBackend();
+ await backend.initialize();
+ const now = Date.now();
+ const liveSession = {
+ sessionId: "live",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: now - 10_000,
+ updatedAt: now - 1_000,
+ };
+ await backend.createSession(liveSession);
+ await backend.appendChunk(
+ liveSession,
+ 0,
+ new Blob(["live!"], { type: "video/webm" }),
+ );
+ const idleSession = {
+ sessionId: "idle",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: now - 10 * 60_000,
+ updatedAt: now - 5 * 60_000,
+ };
+ await backend.createSession(idleSession);
+ await backend.appendChunk(
+ idleSession,
+ 0,
+ new Blob(["idle!"], { type: "video/webm" }),
+ );
+
+ const recovered = await recoverOrphanedRecordingSpools(backend, {
+ minIdleMs: 60_000,
+ });
+
+ expect(recovered.map((item) => item.sessionId)).toEqual(["idle"]);
+ // The skipped live session keeps its data untouched.
+ expect(backend.getSessionCount()).toBe(2);
+ expect(backend.getChunkCount("live")).toBe(1);
+ });
+
+ it("touch refreshes updatedAt so paused recordings stay invisible to recovery sweeps", async () => {
+ const backend = new MemoryRecordingSpoolBackend();
+ const spool = await RecordingSpool.create(
+ { mimeType: "video/webm" },
+ backend,
+ );
+ await spool.appendChunk(new Blob(["chunk"], { type: "video/webm" }));
+ await spool.flush();
+
+ // Simulate a long pause: backdate the persisted session past the idle
+ // threshold, then heartbeat. The sweep must skip the touched session.
+ const [session] = await backend.listSessions();
+ if (!session) throw new Error("expected a session");
+ await backend.createSession({
+ ...session,
+ updatedAt: Date.now() - 10 * 60_000,
+ });
+
+ await spool.touch();
+
+ const recovered = await recoverOrphanedRecordingSpools(backend, {
+ minIdleMs: 60_000,
+ });
+ expect(recovered).toEqual([]);
+ expect(backend.getChunkCount(spool.sessionId)).toBe(1);
+ });
+
+ it("touch failures do not poison the spool write queue", async () => {
+ const backend = new MemoryRecordingSpoolBackend();
+ const spool = await RecordingSpool.create(
+ { mimeType: "video/webm" },
+ backend,
+ );
+ await spool.appendChunk(new Blob(["one"], { type: "video/webm" }));
+ await spool.flush();
+
+ const originalCreateSession = backend.createSession.bind(backend);
+ backend.createSession = async () => {
+ throw new Error("touch write failed");
+ };
+ await expect(spool.touch()).resolves.toBeUndefined();
+ backend.createSession = originalCreateSession;
+
+ await spool.appendChunk(new Blob(["two"], { type: "video/webm" }));
+ await spool.flush();
+ expect(backend.getChunkCount(spool.sessionId)).toBe(2);
+ });
+
+ it("deletes recovered spools only when explicitly dismissed", async () => {
+ const backend = new MemoryRecordingSpoolBackend();
+ await backend.initialize();
+ await backend.createSession({
+ sessionId: "dismiss-me",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 100,
+ updatedAt: 200,
+ });
+ await backend.appendChunk(
+ {
+ sessionId: "dismiss-me",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 100,
+ updatedAt: 200,
+ },
+ 0,
+ new Blob(["stale"], { type: "video/webm" }),
+ );
+
+ await deleteRecoveredRecordingSpool("dismiss-me", backend);
+
+ expect(backend.getSessionCount()).toBe(0);
+ expect(backend.getChunkCount("dismiss-me")).toBe(0);
+ });
+
+ it("preserves sessions that fail during recovery so they can be retried later", async () => {
+ const backend = new MemoryRecordingSpoolBackend({
+ readFailureSessionId: "stuck",
+ });
+ await backend.initialize();
+ await backend.createSession({
+ sessionId: "stuck",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 100,
+ updatedAt: 200,
+ });
+ await backend.appendChunk(
+ {
+ sessionId: "stuck",
+ mimeType: "video/webm",
+ totalBytes: 5,
+ chunkCount: 1,
+ createdAt: 100,
+ updatedAt: 200,
+ },
+ 0,
+ new Blob(["stuck"], { type: "video/webm" }),
+ );
+
+ const recovered = await recoverOrphanedRecordingSpools(backend);
+
+ expect(recovered).toEqual([]);
+ expect(backend.getSessionCount()).toBe(1);
+ expect(backend.getChunkCount("stuck")).toBe(1);
+ });
+});
diff --git a/packages/recorder-core/src/recording-spool.ts b/packages/recorder-core/src/recording-spool.ts
new file mode 100644
index 000000000..3343f3d62
--- /dev/null
+++ b/packages/recorder-core/src/recording-spool.ts
@@ -0,0 +1,494 @@
+export type RecordingSpoolSessionRecord = {
+ sessionId: string;
+ mimeType: string;
+ totalBytes: number;
+ chunkCount: number;
+ createdAt: number;
+ updatedAt: number;
+};
+
+type RecordingSpoolChunk = {
+ sessionId: string;
+ index: number;
+ blob: Blob;
+};
+
+export interface RecordingSpoolBackend {
+ initialize(): Promise<void>;
+ createSession(session: RecordingSpoolSessionRecord): Promise<void>;
+ appendChunk(
+ session: RecordingSpoolSessionRecord,
+ index: number,
+ chunk: Blob,
+ ): Promise<void>;
+ readChunks(sessionId: string): Promise<Blob[]>;
+ listSessions(): Promise<RecordingSpoolSessionRecord[]>;
+ deleteSession(sessionId: string): Promise<void>;
+ /** Keyed lookup; backends without it fall back to listSessions(). */
+ getSession?(sessionId: string): Promise<RecordingSpoolSessionRecord | null>;
+}
+
+export type RecoveredRecordingSpool = RecordingSpoolSessionRecord & {
+ blob: Blob;
+};
+
+const DATABASE_NAME = "cap-recording-spool";
+const DATABASE_VERSION = 1;
+const SESSIONS_STORE = "sessions";
+const CHUNKS_STORE = "chunks";
+const DEFAULT_MAX_PENDING_CHUNK_BYTES = 32 * 1024 * 1024;
+
+// Liveness contract between live recorders and recovery sweeps: a spool whose
+// session was updated within this window must be treated as live and never
+// offered as "recovered" (dismissing a recovered spool deletes the live
+// session's crash backup out from under it). Chunk writes alone are not a
+// reliable liveness signal — a paused MediaRecorder produces no chunks — so
+// recorders also call RecordingSpool.touch() on the heartbeat interval below.
+// The window is sized at 3x the worst-case heartbeat cadence: background tabs
+// under Chrome's intensive timer throttling fire intervals as rarely as once
+// per minute.
+export const RECORDING_SPOOL_LIVE_MIN_IDLE_MS = 3 * 60 * 1000;
+export const RECORDING_SPOOL_HEARTBEAT_INTERVAL_MS = 15 * 1000;
+
+const normalizeError = (error: unknown) =>
+ error instanceof Error ? error : new Error(String(error));
+
+const requestToPromise = <T>(request: IDBRequest<T>) =>
+ new Promise<T>((resolve, reject) => {
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(normalizeError(request.error));
+ });
+
+const transactionToPromise = (transaction: IDBTransaction) =>
+ new Promise<void>((resolve, reject) => {
+ transaction.oncomplete = () => resolve();
+ transaction.onabort = () => reject(normalizeError(transaction.error));
+ transaction.onerror = () => reject(normalizeError(transaction.error));
+ });
+
+const createSessionId = () => {
+ if (
+ typeof crypto !== "undefined" &&
+ typeof crypto.randomUUID === "function"
+ ) {
+ return crypto.randomUUID();
+ }
+
+ return `recording-${Date.now()}-${Math.random().toString(36).slice(2)}`;
+};
+
+export class RecordingSpoolBackpressureError extends Error {
+ constructor() {
+ super("Recording spool could not keep up with capture");
+ this.name = "RecordingSpoolBackpressureError";
+ }
+}
+
+class IndexedDbRecordingSpoolBackend implements RecordingSpoolBackend {
+ private databasePromise: Promise<IDBDatabase> | null = null;
+
+ async initialize() {
+ await this.openDatabase();
+ }
+
+ async createSession(session: RecordingSpoolSessionRecord) {
+ const database = await this.openDatabase();
+ const transaction = database.transaction(SESSIONS_STORE, "readwrite");
+ transaction.objectStore(SESSIONS_STORE).put(session);
+ await transactionToPromise(transaction);
+ }
+
+ async appendChunk(
+ session: RecordingSpoolSessionRecord,
+ index: number,
+ chunk: Blob,
+ ) {
+ const database = await this.openDatabase();
+ const transaction = database.transaction(
+ [SESSIONS_STORE, CHUNKS_STORE],
+ "readwrite",
+ );
+ transaction.objectStore(SESSIONS_STORE).put(session);
+ transaction.objectStore(CHUNKS_STORE).put({
+ sessionId: session.sessionId,
+ index,
+ blob: chunk,
+ } satisfies RecordingSpoolChunk);
+ await transactionToPromise(transaction);
+ }
+
+ async readChunks(sessionId: string) {
+ const database = await this.openDatabase();
+ const transaction = database.transaction(CHUNKS_STORE, "readonly");
+ const index = transaction.objectStore(CHUNKS_STORE).index("by-session");
+ const records = await requestToPromise(
+ index.getAll(IDBKeyRange.only(sessionId)),
+ );
+ await transactionToPromise(transaction);
+ return (records as RecordingSpoolChunk[]).map((record) => record.blob);
+ }
+
+ async listSessions() {
+ const database = await this.openDatabase();
+ const transaction = database.transaction(SESSIONS_STORE, "readonly");
+ const records = await requestToPromise(
+ transaction.objectStore(SESSIONS_STORE).getAll(),
+ );
+ await transactionToPromise(transaction);
+ return records as RecordingSpoolSessionRecord[];
+ }
+
+ async getSession(sessionId: string) {
+ const database = await this.openDatabase();
+ const transaction = database.transaction(SESSIONS_STORE, "readonly");
+ const record = await requestToPromise(
+ transaction.objectStore(SESSIONS_STORE).get(sessionId),
+ );
+ await transactionToPromise(transaction);
+ return (record as RecordingSpoolSessionRecord | undefined) ?? null;
+ }
+
+ async deleteSession(sessionId: string) {
+ const database = await this.openDatabase();
+ const existingChunks = await this.readChunkKeys(sessionId);
+ const transaction = database.transaction(
+ [SESSIONS_STORE, CHUNKS_STORE],
+ "readwrite",
+ );
+ transaction.objectStore(SESSIONS_STORE).delete(sessionId);
+ const chunksStore = transaction.objectStore(CHUNKS_STORE);
+ existingChunks.forEach((key) => {
+ chunksStore.delete(key);
+ });
+ await transactionToPromise(transaction);
+ }
+
+ private openDatabase() {
+ if (!this.databasePromise) {
+ this.databasePromise = new Promise<IDBDatabase>((resolve, reject) => {
+ if (typeof indexedDB === "undefined") {
+ reject(new Error("IndexedDB is not available"));
+ return;
+ }
+
+ const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
+ request.onupgradeneeded = () => {
+ const database = request.result;
+ if (!database.objectStoreNames.contains(SESSIONS_STORE)) {
+ database.createObjectStore(SESSIONS_STORE, {
+ keyPath: "sessionId",
+ });
+ }
+ if (!database.objectStoreNames.contains(CHUNKS_STORE)) {
+ const chunksStore = database.createObjectStore(CHUNKS_STORE, {
+ keyPath: ["sessionId", "index"],
+ });
+ chunksStore.createIndex("by-session", "sessionId", {
+ unique: false,
+ });
+ }
+ };
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(normalizeError(request.error));
+ });
+ }
+
+ return this.databasePromise;
+ }
+
+ private async readChunkKeys(sessionId: string) {
+ const database = await this.openDatabase();
+ const transaction = database.transaction(CHUNKS_STORE, "readonly");
+ const index = transaction.objectStore(CHUNKS_STORE).index("by-session");
+ const keys = await requestToPromise(
+ index.getAllKeys(IDBKeyRange.only(sessionId)),
+ );
+ await transactionToPromise(transaction);
+ return keys;
+ }
+}
+
+export class RecordingSpool {
+ private session: RecordingSpoolSessionRecord;
+ private nextChunkIndex = 0;
+ private pendingWrite = Promise.resolve();
+ private pendingChunks: Blob[] = [];
+ private pendingChunkBytes = 0;
+ private writeError: Error | null = null;
+ private disposed = false;
+
+ private constructor(
+ private readonly backend: RecordingSpoolBackend,
+ session: RecordingSpoolSessionRecord,
+ private readonly maxPendingChunkBytes: number,
+ ) {
+ this.session = session;
+ }
+
+ static async create(
+ options: {
+ mimeType: string;
+ sessionId?: string;
+ maxPendingChunkBytes?: number;
+ },
+ backend: RecordingSpoolBackend = new IndexedDbRecordingSpoolBackend(),
+ ) {
+ const now = Date.now();
+ const session = {
+ sessionId: options.sessionId ?? createSessionId(),
+ mimeType: options.mimeType,
+ totalBytes: 0,
+ chunkCount: 0,
+ createdAt: now,
+ updatedAt: now,
+ } satisfies RecordingSpoolSessionRecord;
+
+ await backend.initialize();
+ await backend.createSession(session);
+
+ return new RecordingSpool(
+ backend,
+ session,
+ options.maxPendingChunkBytes ?? DEFAULT_MAX_PENDING_CHUNK_BYTES,
+ );
+ }
+
+ get sessionId() {
+ return this.session.sessionId;
+ }
+
+ get totalBytes() {
+ return this.session.totalBytes;
+ }
+
+ get chunkCount() {
+ return this.session.chunkCount;
+ }
+
+ appendChunk(chunk: Blob) {
+ if (this.disposed) {
+ return Promise.reject(new Error("Recording spool has been disposed"));
+ }
+
+ if (this.writeError) {
+ return Promise.reject(this.writeError);
+ }
+
+ this.pendingChunks.push(chunk);
+ this.pendingChunkBytes += chunk.size;
+ if (this.pendingChunkBytes > this.maxPendingChunkBytes) {
+ this.writeError = new RecordingSpoolBackpressureError();
+ return Promise.reject(this.writeError);
+ }
+
+ return this.enqueue(async () => {
+ const index = this.nextChunkIndex;
+ const updatedSession = {
+ ...this.session,
+ totalBytes: this.session.totalBytes + chunk.size,
+ chunkCount: this.session.chunkCount + 1,
+ updatedAt: Date.now(),
+ } satisfies RecordingSpoolSessionRecord;
+
+ await this.backend.appendChunk(updatedSession, index, chunk);
+ const persistedChunk = this.pendingChunks.shift();
+ if (persistedChunk) {
+ this.pendingChunkBytes = Math.max(
+ 0,
+ this.pendingChunkBytes - persistedChunk.size,
+ );
+ }
+ this.nextChunkIndex = index + 1;
+ this.session = updatedSession;
+ });
+ }
+
+ // Heartbeat for the liveness contract above: refreshes the session's
+ // updatedAt without writing a chunk so paused recordings stay recognisably
+ // live to recovery sweeps in other tabs. Failures are swallowed and do not
+ // poison the write queue — a missed heartbeat must never degrade an
+ // otherwise healthy spool.
+ touch(): Promise<void> {
+ if (this.disposed || this.writeError) {
+ return Promise.resolve();
+ }
+
+ const operation = this.pendingWrite.then(async () => {
+ if (this.disposed || this.writeError) return;
+ const updatedSession = {
+ ...this.session,
+ updatedAt: Date.now(),
+ } satisfies RecordingSpoolSessionRecord;
+ await this.backend.createSession(updatedSession);
+ this.session = updatedSession;
+ });
+ this.pendingWrite = operation.then(
+ () => undefined,
+ () => undefined,
+ );
+
+ return operation.catch(() => undefined);
+ }
+
+ async flush() {
+ await this.pendingWrite;
+ if (this.writeError) {
+ throw this.writeError;
+ }
+ }
+
+ async toBlob() {
+ await this.flush();
+ return this.readPersistedBlob();
+ }
+
+ async recoverBlob() {
+ await this.pendingWrite;
+ const persistedBlob = await this.readPersistedBlob();
+ if (this.pendingChunks.length === 0) {
+ return persistedBlob;
+ }
+
+ return new Blob(
+ persistedBlob
+ ? [persistedBlob, ...this.pendingChunks]
+ : [...this.pendingChunks],
+ { type: this.session.mimeType },
+ );
+ }
+
+ private async readPersistedBlob() {
+ const chunks = await this.backend.readChunks(this.session.sessionId);
+ if (chunks.length === 0) {
+ return null;
+ }
+
+ return new Blob(chunks, { type: this.session.mimeType });
+ }
+
+ async dispose() {
+ if (this.disposed) {
+ return;
+ }
+
+ this.disposed = true;
+ this.pendingChunks = [];
+ this.pendingChunkBytes = 0;
+ try {
+ await this.pendingWrite;
+ } catch {}
+ await this.backend.deleteSession(this.session.sessionId);
+ }
+
+ private enqueue(task: () => Promise<void>) {
+ const operation = this.pendingWrite.then(async () => {
+ if (this.writeError) {
+ throw this.writeError;
+ }
+
+ await task();
+ });
+ this.pendingWrite = operation.then(
+ () => undefined,
+ () => undefined,
+ );
+
+ return operation.catch((error) => {
+ this.writeError = normalizeError(error);
+ throw this.writeError;
+ });
+ }
+}
+
+export const canUseRecordingSpool = () =>
+ typeof window !== "undefined" && typeof indexedDB !== "undefined";
+
+export const recoverOrphanedRecordingSpools = async (
+ backend: RecordingSpoolBackend = new IndexedDbRecordingSpoolBackend(),
+ options: { minIdleMs?: number } = {},
+) => {
+ await backend.initialize();
+ const sessions = await backend.listSessions();
+ const recovered: RecoveredRecordingSpool[] = [];
+ const minIdleMs = options.minIdleMs ?? 0;
+ const now = Date.now();
+
+ for (const session of sessions) {
+ // A session updated this recently may belong to a recording that is
+ // live in another tab (or just starting in this one). Recovering it
+ // would offer the user a "recovered" copy whose dismissal deletes the
+ // live session's crash backup out from under it.
+ if (minIdleMs > 0 && now - session.updatedAt < minIdleMs) {
+ continue;
+ }
+
+ try {
+ const chunks = await backend.readChunks(session.sessionId);
+ if (chunks.length === 0) {
+ await backend.deleteSession(session.sessionId);
+ continue;
+ }
+
+ recovered.push({
+ ...session,
+ blob: new Blob(chunks, { type: session.mimeType }),
+ });
+ } catch (error) {
+ console.error(
+ "Failed to recover orphaned recording spool",
+ session.sessionId,
+ error,
+ );
+ }
+ }
+
+ return recovered.sort((left, right) => right.updatedAt - left.updatedAt);
+};
+
+// Session metadata only — no chunk reads, no Blob construction. Startup
+// sweeps that just reconcile bookkeeping use this instead of
+// recoverOrphanedRecordingSpools, which materialises every stranded
+// recording's bytes.
+export const listRecordingSpoolSessions = async (
+ backend: RecordingSpoolBackend = new IndexedDbRecordingSpoolBackend(),
+): Promise<RecordingSpoolSessionRecord[]> => {
+ await backend.initialize();
+ const sessions = await backend.listSessions();
+ return sessions.sort((left, right) => right.updatedAt - left.updatedAt);
+};
+
+// Recover a single session without reading every other session's chunks;
+// retry and download paths know exactly which spool they need, so a full
+// recoverOrphanedRecordingSpools sweep would be wasted I/O.
+export const recoverRecordingSpoolSession = async (
+ sessionId: string,
+ backend: RecordingSpoolBackend = new IndexedDbRecordingSpoolBackend(),
+): Promise<RecoveredRecordingSpool | null> => {
+ await backend.initialize();
+ const session = backend.getSession
+ ? await backend.getSession(sessionId)
+ : ((await backend.listSessions()).find(
+ (entry) => entry.sessionId === sessionId,
+ ) ?? null);
+ if (!session) {
+ return null;
+ }
+
+ const chunks = await backend.readChunks(session.sessionId);
+ if (chunks.length === 0) {
+ return null;
+ }
+
+ return {
+ ...session,
+ blob: new Blob(chunks, { type: session.mimeType }),
+ };
+};
+
+export const deleteRecoveredRecordingSpool = async (
+ sessionId: string,
+ backend: RecordingSpoolBackend = new IndexedDbRecordingSpoolBackend(),
+) => {
+ await backend.initialize();
+ await backend.deleteSession(sessionId);
+};