mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-18 16:08:56 +00:00
fix(studio): recovery drafts are kept by each project's own server, never the browser (#7904)
* fix(studio): recovery drafts are kept by each project's own server, never the browser * fix(studio): a restored draft stays offered when Studio settles which composition is open * fix(studio): a draft read never waits on a pipe or loads an oversized record * test(studio): the draft read's child fixture is an entry point, and its note sits in the test * chore(studio-server): size budget covers the recovery-draft route * chore(cli): unpacked size budget covers the recovery-draft route
This commit is contained in:
@@ -837,6 +837,26 @@ describe("external file change coordinator", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// Studio settles which composition is open just after load, while the draft's file stays the same.
|
||||
it("keeps a restored draft when the open composition changes but the draft's file does not", async () => {
|
||||
const { captured, rerender } = await mountCoordinator({
|
||||
recoveryFilePath: "index.html",
|
||||
loadConflictSnapshot: vi.fn(async () => ({
|
||||
kind: "conflict" as const,
|
||||
projectId: "project-a",
|
||||
filePath: "index.html",
|
||||
externalVersion: "v2",
|
||||
externalContent: "external",
|
||||
studioContent: "studio",
|
||||
createdAt: 100,
|
||||
})),
|
||||
});
|
||||
await vi.waitFor(() => expect(captured.handle?.blocked?.status).toBe("conflict"));
|
||||
|
||||
await rerender({ activeCompPath: null });
|
||||
await vi.waitFor(() => expect(captured.handle?.blocked?.status).toBe("conflict"));
|
||||
});
|
||||
|
||||
it("retains the final local candidate when a drain fails", async () => {
|
||||
const failure = new Error("network unavailable");
|
||||
const persistFailureSnapshot = vi.fn(async () => undefined);
|
||||
|
||||
@@ -248,7 +248,7 @@ export function useExternalFileChangeCoordinator({
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [loadConflictSnapshot, projectId, recoveryFilePath, setBlocked]);
|
||||
}, [loadConflictSnapshot, projectId, activeCompPath, recoveryFilePath, setBlocked]);
|
||||
|
||||
// What a settled change owes: thumbnails (unless its own write's echo brings them), then reloads.
|
||||
const deliverOwed = useCallback(
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { createStudioApi } from "@hyperframes/studio-server";
|
||||
import { IDBFactory } from "fake-indexeddb";
|
||||
import { mkdtempSync, readdirSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
createMemoryExternalConflictStorage,
|
||||
@@ -9,6 +13,27 @@ import {
|
||||
} from "./externalConflictStorage";
|
||||
import { StudioFileConflictError } from "./studioSaveDiagnostics";
|
||||
|
||||
const made: string[] = [];
|
||||
|
||||
/** Studio's real API for one project, "demo", answering the store's fetches. */
|
||||
function serveProject(): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hf-drafts-"));
|
||||
made.push(dir);
|
||||
const api = createStudioApi({
|
||||
listProjects: () => [],
|
||||
resolveProject: async (id: string) => (id === "demo" ? { id, dir, title: "Demo" } : null),
|
||||
bundle: async () => null,
|
||||
lint: async () => ({ findings: [] }),
|
||||
runtimeUrl: "/api/runtime.js",
|
||||
rendersDir: () => join(dir, "renders"),
|
||||
startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "" }),
|
||||
});
|
||||
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
|
||||
api.fetch(new Request(`http://localhost${input.replace(/^\/api/, "")}`, init)),
|
||||
);
|
||||
return dir;
|
||||
}
|
||||
|
||||
describe("external conflict snapshots", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("indexedDB", new IDBFactory());
|
||||
@@ -17,6 +42,7 @@ describe("external conflict snapshots", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("durably records both complete file versions before resolution", async () => {
|
||||
@@ -54,8 +80,8 @@ describe("external conflict snapshots", () => {
|
||||
expect(await storage.get("project-a", "index.html")).toEqual(snapshot);
|
||||
});
|
||||
|
||||
it("persists, loads, and deletes a snapshot through the production IndexedDB adapter", async () => {
|
||||
vi.spyOn(Date, "now").mockReturnValue(1234);
|
||||
it("persists, loads, and deletes a draft through the project's own server", async () => {
|
||||
const project = serveProject();
|
||||
const conflict = new StudioFileConflictError({
|
||||
filePath: "index.html",
|
||||
currentVersion: "v2",
|
||||
@@ -63,24 +89,50 @@ describe("external conflict snapshots", () => {
|
||||
attemptedContent: "studio full file",
|
||||
});
|
||||
|
||||
await persistExternalConflictSnapshot("indexeddb-project", conflict);
|
||||
await expect(loadExternalConflictSnapshot("indexeddb-project", "index.html")).resolves.toEqual({
|
||||
await persistExternalConflictSnapshot("demo", conflict);
|
||||
expect(readdirSync(join(project, ".hyperframes", "recovery"))).toHaveLength(1);
|
||||
await expect(loadExternalConflictSnapshot("demo", "index.html")).resolves.toMatchObject({
|
||||
kind: "conflict",
|
||||
projectId: "indexeddb-project",
|
||||
projectId: "demo",
|
||||
filePath: "index.html",
|
||||
externalVersion: "v2",
|
||||
externalContent: "external full file",
|
||||
studioContent: "studio full file",
|
||||
createdAt: 1234,
|
||||
});
|
||||
await deleteExternalConflictSnapshot("indexeddb-project", "index.html");
|
||||
await expect(
|
||||
loadExternalConflictSnapshot("indexeddb-project", "index.html"),
|
||||
).resolves.toBeNull();
|
||||
await deleteExternalConflictSnapshot("demo", "index.html");
|
||||
await expect(loadExternalConflictSnapshot("demo", "index.html")).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("rejects persistence when IndexedDB is unavailable", async () => {
|
||||
vi.stubGlobal("indexedDB", undefined);
|
||||
// Every project previewed on a port shares the origin's IndexedDB, and so does each one's composition code.
|
||||
it("never offers a draft another project's code planted in the browser's shared IndexedDB", async () => {
|
||||
serveProject();
|
||||
const open = indexedDB.open("hyperframes-studio-external-conflicts", 1);
|
||||
open.onupgradeneeded = () => open.result.createObjectStore("file-conflicts");
|
||||
const db = await new Promise<IDBDatabase>(
|
||||
(resolve) => (open.onsuccess = () => resolve(open.result)),
|
||||
);
|
||||
const planted = db.transaction("file-conflicts", "readwrite");
|
||||
planted.objectStore("file-conflicts").put(
|
||||
{
|
||||
kind: "failed",
|
||||
projectId: "demo",
|
||||
filePath: "index.html",
|
||||
externalVersion: null,
|
||||
externalContent: null,
|
||||
studioContent: "<script>planted</script>",
|
||||
failureMessage: "Recovered draft",
|
||||
createdAt: Date.now(),
|
||||
},
|
||||
"demo\0index.html",
|
||||
);
|
||||
await new Promise((resolve) => (planted.oncomplete = resolve));
|
||||
db.close();
|
||||
|
||||
await expect(loadExternalConflictSnapshot("demo", "index.html")).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("rejects persistence when the server cannot keep the draft", async () => {
|
||||
vi.stubGlobal("fetch", async () => new Response("{}", { status: 500 }));
|
||||
const conflict = new StudioFileConflictError({
|
||||
filePath: "index.html",
|
||||
currentVersion: "v2",
|
||||
@@ -88,8 +140,8 @@ describe("external conflict snapshots", () => {
|
||||
attemptedContent: "studio",
|
||||
});
|
||||
|
||||
await expect(persistExternalConflictSnapshot("project-a", conflict)).rejects.toThrow(
|
||||
"IndexedDB is unavailable; conflict recovery snapshot was not saved",
|
||||
await expect(persistExternalConflictSnapshot("demo", conflict)).rejects.toThrow(
|
||||
"Recovery draft storage failed (500)",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { StudioFileConflictError } from "./studioSaveDiagnostics";
|
||||
import { studioApiFetch } from "./studioApiFetch";
|
||||
|
||||
interface ExternalRecoverySnapshotBase {
|
||||
projectId: string;
|
||||
@@ -19,10 +20,6 @@ export interface ExternalConflictStorage {
|
||||
delete(projectId: string, filePath: string): Promise<void>;
|
||||
}
|
||||
|
||||
const DB_NAME = "hyperframes-studio-external-conflicts";
|
||||
const DB_VERSION = 1;
|
||||
const STORE_NAME = "file-conflicts";
|
||||
|
||||
function key(projectId: string, filePath: string): string {
|
||||
return `${projectId}\0${filePath}`;
|
||||
}
|
||||
@@ -43,85 +40,46 @@ export function createMemoryExternalConflictStorage(): ExternalConflictStorage {
|
||||
};
|
||||
}
|
||||
|
||||
function openDb(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!globalThis.indexedDB) {
|
||||
reject(new Error("IndexedDB is unavailable; conflict recovery snapshot was not saved"));
|
||||
return;
|
||||
}
|
||||
const request = globalThis.indexedDB.open(DB_NAME, DB_VERSION);
|
||||
request.onupgradeneeded = () => {
|
||||
if (!request.result.objectStoreNames.contains(STORE_NAME)) {
|
||||
request.result.createObjectStore(STORE_NAME);
|
||||
}
|
||||
function draftUrl(projectId: string, filePath: string): string {
|
||||
return `/api/projects/${encodeURIComponent(projectId)}/recovery-drafts/${encodeURIComponent(filePath)}`;
|
||||
}
|
||||
|
||||
async function draftRequest(
|
||||
projectId: string,
|
||||
filePath: string,
|
||||
init?: RequestInit,
|
||||
): Promise<Response> {
|
||||
const res = await studioApiFetch(draftUrl(projectId, filePath), init);
|
||||
if (!res.ok) throw new Error(`Recovery draft storage failed (${res.status})`);
|
||||
return res;
|
||||
}
|
||||
|
||||
/** Kept by the project's own server: an origin-wide browser store is shared with every project on the port. */
|
||||
const projectStorage: ExternalConflictStorage = {
|
||||
async get(projectId, filePath) {
|
||||
const { draft } = (await (await draftRequest(projectId, filePath)).json()) as {
|
||||
draft: ExternalConflictSnapshot | null;
|
||||
};
|
||||
request.onerror = () => reject(request.error ?? new Error("Failed to open conflict storage"));
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
});
|
||||
}
|
||||
return draft?.projectId === projectId && draft.filePath === filePath ? draft : null;
|
||||
},
|
||||
async set(snapshot) {
|
||||
await draftRequest(snapshot.projectId, snapshot.filePath, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(snapshot),
|
||||
});
|
||||
},
|
||||
async delete(projectId, filePath) {
|
||||
await draftRequest(projectId, filePath, { method: "DELETE" });
|
||||
},
|
||||
};
|
||||
|
||||
function withStore<T>(
|
||||
mode: IDBTransactionMode,
|
||||
callback: (store: IDBObjectStore) => IDBRequest<T>,
|
||||
): Promise<T> {
|
||||
return openDb().then(
|
||||
(db) =>
|
||||
new Promise<T>((resolve, reject) => {
|
||||
const transaction = db.transaction(STORE_NAME, mode);
|
||||
const request = callback(transaction.objectStore(STORE_NAME));
|
||||
let result!: T;
|
||||
request.onerror = () => reject(request.error ?? new Error("Conflict storage failed"));
|
||||
request.onsuccess = () => {
|
||||
result = request.result;
|
||||
};
|
||||
transaction.oncomplete = () => {
|
||||
db.close();
|
||||
resolve(result);
|
||||
};
|
||||
transaction.onerror = () => {
|
||||
db.close();
|
||||
reject(transaction.error ?? new Error("Conflict storage transaction failed"));
|
||||
};
|
||||
transaction.onabort = () => {
|
||||
db.close();
|
||||
reject(transaction.error ?? new Error("Conflict storage transaction was aborted"));
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function createIndexedDbExternalConflictStorage(): ExternalConflictStorage {
|
||||
return {
|
||||
async get(projectId, filePath) {
|
||||
return (
|
||||
(await withStore<ExternalConflictSnapshot | undefined>("readonly", (store) =>
|
||||
store.get(key(projectId, filePath)),
|
||||
)) ?? null
|
||||
);
|
||||
},
|
||||
async set(snapshot) {
|
||||
await withStore<IDBValidKey>("readwrite", (store) =>
|
||||
store.put(snapshot, key(snapshot.projectId, snapshot.filePath)),
|
||||
);
|
||||
},
|
||||
async delete(projectId, filePath) {
|
||||
await withStore<undefined>("readwrite", (store) => store.delete(key(projectId, filePath)));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const indexedDbStorage = createIndexedDbExternalConflictStorage();
|
||||
|
||||
/**
|
||||
* Persist a conflict before offering destructive recovery actions.
|
||||
* Callers must await this promise: rejection means the Studio draft was not saved durably and
|
||||
* must remain available in memory while the storage failure is surfaced to the user.
|
||||
*/
|
||||
/** Saved before destructive recovery is offered; on a rejection the draft stays only in memory and the user is told. */
|
||||
export async function persistExternalConflictSnapshot(
|
||||
projectId: string,
|
||||
conflict: StudioFileConflictError,
|
||||
): Promise<void> {
|
||||
await indexedDbStorage.set({
|
||||
await projectStorage.set({
|
||||
kind: "conflict",
|
||||
projectId,
|
||||
filePath: conflict.filePath,
|
||||
@@ -132,11 +90,7 @@ export async function persistExternalConflictSnapshot(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the final Studio candidate after its file write fails.
|
||||
* Callers must await this promise: rejection means the Studio draft was not saved durably and
|
||||
* must remain available in memory while the storage failure is surfaced to the user.
|
||||
*/
|
||||
/** Studio's final candidate after its file write failed; awaited like persistExternalConflictSnapshot. */
|
||||
export async function persistExternalFailureSnapshot(
|
||||
projectId: string,
|
||||
filePath: string,
|
||||
@@ -145,7 +99,7 @@ export async function persistExternalFailureSnapshot(
|
||||
externalContent: string | null,
|
||||
error: unknown,
|
||||
): Promise<void> {
|
||||
await indexedDbStorage.set({
|
||||
await projectStorage.set({
|
||||
kind: "failed",
|
||||
projectId,
|
||||
filePath,
|
||||
@@ -161,12 +115,12 @@ export async function loadExternalConflictSnapshot(
|
||||
projectId: string,
|
||||
filePath: string,
|
||||
): Promise<ExternalConflictSnapshot | null> {
|
||||
return indexedDbStorage.get(projectId, filePath);
|
||||
return projectStorage.get(projectId, filePath);
|
||||
}
|
||||
|
||||
export async function deleteExternalConflictSnapshot(
|
||||
projectId: string,
|
||||
filePath: string,
|
||||
): Promise<void> {
|
||||
await indexedDbStorage.delete(projectId, filePath);
|
||||
await projectStorage.delete(projectId, filePath);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user