feat(web): studio worlds, camera-view/offscreen environment parity, material and undo coverage
Environment lighting: - ship all eight desktop studiolights/world datasets (WBENV1 float32) and a shared loader used by both the main viewport and the offscreen worker - add the N-panel "studio 环境" selector - rotate the world background together with the environment (backgroundRotation/backgroundIntensity), so camera view and offscreen renders match the desktop Mapping-node behaviour Verification (Chromium, OPFS, NOT_CLAIMED): - environment lighting + 8 world pixel identity - camera-view rotation correspondence (camera matrices, 207 samples) - offscreen vs on-screen background parity after hiding geometry (1305 samples) - metals case extended with material-field OPFS roundtrip - material Principled edits and rename undo/redo - eight studio worlds: pairwise frame differences + luminance rank correlation - undo history depth capped at 64 steps and undo across OPFS save/reopen Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,7 @@ import {
|
||||
type AssetCatalogManifestV2IR,
|
||||
} from "../../../protocol/asset-catalog-v2";
|
||||
import type { ErrorCode } from "../../../protocol/error";
|
||||
import type { KvDatabase, KvStore, KvTransaction } from "./opfs-kv";
|
||||
|
||||
export const ASSET_CATALOG_INDEX_V1_ID = "asset-catalog:index:v1" as const;
|
||||
export const ASSET_CATALOG_INDEX_V2_ID = "asset-catalog:index:v2" as const;
|
||||
@@ -89,7 +90,7 @@ async function sha256(value: unknown): Promise<string> {
|
||||
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
function transactionComplete(transaction: IDBTransaction, failure: () => Error | undefined): Promise<void> {
|
||||
function transactionComplete(transaction: KvTransaction, failure: () => Error | undefined): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
transaction.oncomplete = () => resolve();
|
||||
transaction.onerror = () => reject(failure() ?? transaction.error ?? new AssetCatalogIndexedDBMigrationError("STORAGE_TRANSACTION", "Catalog migration transaction failed"));
|
||||
@@ -97,7 +98,7 @@ function transactionComplete(transaction: IDBTransaction, failure: () => Error |
|
||||
});
|
||||
}
|
||||
|
||||
function readRow(store: IDBObjectStore, id: string): Promise<StoredRow | undefined> {
|
||||
function readRow(store: KvStore, id: string): Promise<StoredRow | undefined> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = store.get(id);
|
||||
request.onsuccess = () => resolve(request.result as StoredRow | undefined);
|
||||
@@ -105,7 +106,7 @@ function readRow(store: IDBObjectStore, id: string): Promise<StoredRow | undefin
|
||||
});
|
||||
}
|
||||
|
||||
function assertStores(database: IDBDatabase, settingStore: string, migrationStore: string): void {
|
||||
function assertStores(database: KvDatabase, settingStore: string, migrationStore: string): void {
|
||||
if (!database.objectStoreNames.contains(settingStore) || !database.objectStoreNames.contains(migrationStore)) {
|
||||
throw new AssetCatalogIndexedDBMigrationError("STORAGE_TRANSACTION", "Catalog migration stores are unavailable");
|
||||
}
|
||||
@@ -124,7 +125,7 @@ function parseReceipt(value: unknown): AssetCatalogIndexedDBMigrationReceiptIR {
|
||||
}
|
||||
|
||||
export async function readAssetCatalogIndexedDBIndex(
|
||||
database: IDBDatabase,
|
||||
database: KvDatabase,
|
||||
settingStore = "setting",
|
||||
migrationStore = "migration",
|
||||
): Promise<{ source: StoredRow | undefined; target: StoredRow | undefined; receipt: StoredRow | undefined }> {
|
||||
@@ -139,7 +140,7 @@ export async function readAssetCatalogIndexedDBIndex(
|
||||
}
|
||||
|
||||
export async function migrateAssetCatalogIndexedDB(
|
||||
database: IDBDatabase,
|
||||
database: KvDatabase,
|
||||
options: {
|
||||
settingStore?: string;
|
||||
migrationStore?: string;
|
||||
@@ -213,7 +214,7 @@ export async function migrateAssetCatalogIndexedDB(
|
||||
}
|
||||
|
||||
export async function loadAssetCatalogIndexedDBSnapshot(
|
||||
database: IDBDatabase,
|
||||
database: KvDatabase,
|
||||
options: { settingStore?: string; migrationStore?: string } = {},
|
||||
): Promise<AssetCatalogIndexedDBSnapshotIR> {
|
||||
const loaded = await migrateAssetCatalogIndexedDB(database, options);
|
||||
|
||||
@@ -16,6 +16,7 @@ import type {
|
||||
StorageAssetCatalogSeedIR,
|
||||
} from "../../../protocol/storage";
|
||||
import { ASSET_PREVIEW_CATALOG_HEAD_ID, commitAssetPreviewToOPFS } from "./asset-preview-opfs-commit";
|
||||
import type { KvDatabase, KvStore, KvTransaction } from "./opfs-kv";
|
||||
import { readContentAsset, writeContentAsset } from "./opfs-files";
|
||||
|
||||
export const ASSET_CATALOG_SEED_ID = "asset-catalog:seed:v1" as const;
|
||||
@@ -38,7 +39,7 @@ function stableJSON(value: unknown): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function readStored<T>(store: IDBObjectStore, id: string): Promise<T | undefined> {
|
||||
function readStored<T>(store: KvStore, id: string): Promise<T | undefined> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = store.get(id);
|
||||
request.onsuccess = () => resolve(request.result as T | undefined);
|
||||
@@ -46,7 +47,7 @@ function readStored<T>(store: IDBObjectStore, id: string): Promise<T | undefined
|
||||
});
|
||||
}
|
||||
|
||||
function complete(transaction: IDBTransaction): Promise<void> {
|
||||
function complete(transaction: KvTransaction): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
transaction.oncomplete = () => resolve();
|
||||
transaction.onabort = () => reject(transaction.error ?? new Error("Storage transaction aborted"));
|
||||
@@ -71,14 +72,14 @@ function parseSeed(value: unknown): StorageAssetCatalogSeedIR | null {
|
||||
};
|
||||
}
|
||||
|
||||
async function readSeed(database: IDBDatabase): Promise<StorageAssetCatalogSeedIR | null> {
|
||||
async function readSeed(database: KvDatabase): Promise<StorageAssetCatalogSeedIR | null> {
|
||||
const transaction = database.transaction("setting", "readonly");
|
||||
const row = await readStored<{ id: string; value: unknown }>(transaction.objectStore("setting"), ASSET_CATALOG_SEED_ID);
|
||||
await complete(transaction);
|
||||
return parseSeed(row?.value);
|
||||
}
|
||||
|
||||
export async function readAssetCatalog(database: IDBDatabase): Promise<StorageAssetCatalogResult> {
|
||||
export async function readAssetCatalog(database: KvDatabase): Promise<StorageAssetCatalogResult> {
|
||||
const { source, target } = await readAssetCatalogIndexedDBIndex(database);
|
||||
if (target) {
|
||||
return {
|
||||
@@ -94,7 +95,7 @@ export async function readAssetCatalog(database: IDBDatabase): Promise<StorageAs
|
||||
}
|
||||
|
||||
export async function seedAssetCatalog(
|
||||
database: IDBDatabase,
|
||||
database: KvDatabase,
|
||||
options: {
|
||||
manifest: unknown;
|
||||
projectId?: string;
|
||||
@@ -171,7 +172,7 @@ export async function readAssetCatalogPreview(projectId: string, sha256Value: st
|
||||
}
|
||||
|
||||
export async function commitAssetCatalogPreview(
|
||||
database: IDBDatabase,
|
||||
database: KvDatabase,
|
||||
projectId: string,
|
||||
expectedRevision: number,
|
||||
identity: unknown,
|
||||
@@ -194,7 +195,7 @@ export async function commitAssetCatalogPreview(
|
||||
}
|
||||
|
||||
export async function mergeAssetCatalogManifest(
|
||||
database: IDBDatabase,
|
||||
database: KvDatabase,
|
||||
options: { manifest: unknown; projectId?: string },
|
||||
): Promise<StorageAssetCatalogResult> {
|
||||
const incoming = await parseAssetCatalogManifestV2(options.manifest);
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type AssetPreviewIdentityIR,
|
||||
} from "../../../protocol/asset-preview";
|
||||
import type { ErrorCode } from "../../../protocol/error";
|
||||
import type { KvDatabase, KvStore, KvTransaction } from "./opfs-kv";
|
||||
import {
|
||||
ASSET_CATALOG_INDEX_V2_ID,
|
||||
type AssetCatalogIndexRowV2,
|
||||
@@ -87,7 +88,7 @@ async function sha256Bytes(value: ArrayBuffer): Promise<string> {
|
||||
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
function readRow(store: IDBObjectStore, id: string): Promise<StoredRow | undefined> {
|
||||
function readRow(store: KvStore, id: string): Promise<StoredRow | undefined> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = store.get(id);
|
||||
request.onsuccess = () => resolve(request.result as StoredRow | undefined);
|
||||
@@ -95,7 +96,7 @@ function readRow(store: IDBObjectStore, id: string): Promise<StoredRow | undefin
|
||||
});
|
||||
}
|
||||
|
||||
function transactionComplete(transaction: IDBTransaction, failure: () => Error | undefined): Promise<void> {
|
||||
function transactionComplete(transaction: KvTransaction, failure: () => Error | undefined): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
transaction.oncomplete = () => resolve();
|
||||
transaction.onerror = () => reject(failure() ?? transaction.error ?? new AssetPreviewCatalogCommitError("STORAGE_TRANSACTION", "Preview catalog transaction failed"));
|
||||
@@ -103,7 +104,7 @@ function transactionComplete(transaction: IDBTransaction, failure: () => Error |
|
||||
});
|
||||
}
|
||||
|
||||
async function readCatalog(database: IDBDatabase, settingStore: string): Promise<{ row: StoredRow; manifest: AssetCatalogManifestV2IR }> {
|
||||
async function readCatalog(database: KvDatabase, settingStore: string): Promise<{ row: StoredRow; manifest: AssetCatalogManifestV2IR }> {
|
||||
if (!database.objectStoreNames.contains(settingStore)) {
|
||||
throw new AssetPreviewCatalogCommitError("STORAGE_TRANSACTION", "Catalog setting store is unavailable");
|
||||
}
|
||||
@@ -142,7 +143,7 @@ function previewFromIdentity(identity: AssetPreviewIdentityIR): AssetCatalogV2Pr
|
||||
}
|
||||
|
||||
export async function commitAssetPreviewToOPFS(
|
||||
database: IDBDatabase,
|
||||
database: KvDatabase,
|
||||
projectId: string,
|
||||
expectedRevision: number,
|
||||
identityValue: unknown,
|
||||
@@ -237,7 +238,7 @@ export async function commitAssetPreviewToOPFS(
|
||||
}
|
||||
|
||||
export async function loadCommittedAssetPreviewCatalog(
|
||||
database: IDBDatabase,
|
||||
database: KvDatabase,
|
||||
options: { settingStore?: string; storage?: StorageManager } = {},
|
||||
): Promise<AssetPreviewCatalogCommitResultIR> {
|
||||
const settingStore = options.settingStore ?? "setting";
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
type AssetCatalogV2PreviewIR,
|
||||
} from "../../../protocol/asset-catalog-v2";
|
||||
import type { ErrorCode } from "../../../protocol/error";
|
||||
import type { KvDatabase, KvStore, KvTransaction } from "./opfs-kv";
|
||||
import { ASSET_CATALOG_INDEX_V2_ID } from "./asset-catalog-indexeddb";
|
||||
import { projectLayout } from "./opfs-files";
|
||||
|
||||
@@ -76,7 +77,7 @@ async function sha256Bytes(value: ArrayBuffer): Promise<string> {
|
||||
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
function transactionComplete(transaction: IDBTransaction, failure: () => Error | undefined): Promise<void> {
|
||||
function transactionComplete(transaction: KvTransaction, failure: () => Error | undefined): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
transaction.oncomplete = () => resolve();
|
||||
transaction.onerror = () => reject(failure() ?? transaction.error ?? new AssetPreviewQuarantineError("STORAGE_TRANSACTION", "Preview quarantine transaction failed"));
|
||||
@@ -84,7 +85,7 @@ function transactionComplete(transaction: IDBTransaction, failure: () => Error |
|
||||
});
|
||||
}
|
||||
|
||||
function readRow(store: IDBObjectStore, id: string): Promise<StoredRow | undefined> {
|
||||
function readRow(store: KvStore, id: string): Promise<StoredRow | undefined> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = store.get(id);
|
||||
request.onsuccess = () => resolve(request.result as StoredRow | undefined);
|
||||
@@ -159,7 +160,7 @@ async function quarantinePayload(
|
||||
}
|
||||
|
||||
export async function inspectAssetPreviewWithQuarantine(
|
||||
database: IDBDatabase,
|
||||
database: KvDatabase,
|
||||
projectId: string,
|
||||
assetId: string,
|
||||
options: { settingStore?: string; storage?: StorageManager } = {},
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
type AssetCatalogV2PreviewIR,
|
||||
} from "../../../protocol/asset-catalog-v2";
|
||||
import type { ErrorCode } from "../../../protocol/error";
|
||||
import type { KvDatabase, KvStore, KvTransaction } from "./opfs-kv";
|
||||
import { ASSET_CATALOG_INDEX_V2_ID, type AssetCatalogIndexRowV2 } from "./asset-catalog-indexeddb";
|
||||
import { ASSET_PREVIEW_CATALOG_HEAD_ID } from "./asset-preview-opfs-commit";
|
||||
import { deleteContentAsset } from "./opfs-files";
|
||||
@@ -70,7 +71,7 @@ function receiptId(assetId: string): string {
|
||||
return `${ASSET_PREVIEW_REFERENCE_GC_PREFIX}${assetId}`;
|
||||
}
|
||||
|
||||
function readRow(store: IDBObjectStore, id: string): Promise<StoredRow | undefined> {
|
||||
function readRow(store: KvStore, id: string): Promise<StoredRow | undefined> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = store.get(id);
|
||||
request.onsuccess = () => resolve(request.result as StoredRow | undefined);
|
||||
@@ -78,7 +79,7 @@ function readRow(store: IDBObjectStore, id: string): Promise<StoredRow | undefin
|
||||
});
|
||||
}
|
||||
|
||||
function transactionComplete(transaction: IDBTransaction, failure: () => Error | undefined): Promise<void> {
|
||||
function transactionComplete(transaction: KvTransaction, failure: () => Error | undefined): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
transaction.oncomplete = () => resolve();
|
||||
transaction.onerror = () => reject(failure() ?? transaction.error ?? new AssetPreviewReferenceGCError("STORAGE_TRANSACTION", "Preview reference transaction failed"));
|
||||
@@ -86,7 +87,7 @@ function transactionComplete(transaction: IDBTransaction, failure: () => Error |
|
||||
});
|
||||
}
|
||||
|
||||
async function loadCatalog(database: IDBDatabase, settingStore: string): Promise<{ row: StoredRow; manifest: AssetCatalogManifestV2IR }> {
|
||||
async function loadCatalog(database: KvDatabase, settingStore: string): Promise<{ row: StoredRow; manifest: AssetCatalogManifestV2IR }> {
|
||||
if (!database.objectStoreNames.contains(settingStore)) {
|
||||
throw new AssetPreviewReferenceGCError("STORAGE_TRANSACTION", "Catalog setting store is unavailable");
|
||||
}
|
||||
@@ -98,7 +99,7 @@ async function loadCatalog(database: IDBDatabase, settingStore: string): Promise
|
||||
}
|
||||
|
||||
export async function removeAssetPreviewReference(
|
||||
database: IDBDatabase,
|
||||
database: KvDatabase,
|
||||
projectId: string,
|
||||
expectedRevision: number,
|
||||
assetId: string,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { STORAGE_DATABASE_NAME, STORAGE_SCHEMA_VERSION, upgradeStorageSchema } from './migrations';
|
||||
import { STORAGE_DATABASE_NAME, STORAGE_STORES } from './migrations';
|
||||
import { openKvDatabase, type KvDatabase } from './opfs-kv';
|
||||
|
||||
type PresetFiles = Array<{ name: string; bytes: Uint8Array }>;
|
||||
export interface CameraPresetFS {
|
||||
@@ -16,20 +17,16 @@ function files(value: unknown): PresetFiles {
|
||||
}
|
||||
if (total > 4 * 1024 * 1024) throw new Error('Camera presets exceed 4 MiB'); return value;
|
||||
}
|
||||
async function database(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(STORAGE_DATABASE_NAME, STORAGE_SCHEMA_VERSION);
|
||||
request.onupgradeneeded = event => upgradeStorageSchema(request.result, request.transaction!, event.oldVersion);
|
||||
request.onsuccess = () => { request.result.onversionchange = () => request.result.close(); resolve(request.result); };
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
async function database(): Promise<KvDatabase> {
|
||||
// Presets are work files, so they live in OPFS with the rest of the project
|
||||
// storage rather than in an IndexedDB database.
|
||||
return openKvDatabase(STORAGE_DATABASE_NAME, STORAGE_STORES);
|
||||
}
|
||||
async function read(db: IDBDatabase): Promise<PresetFiles | undefined> {
|
||||
async function read(db: KvDatabase): Promise<PresetFiles | undefined> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction('setting'), request = tx.objectStore('setting').get(KEY);
|
||||
tx.onabort = () => reject(tx.error ?? new Error('Camera preset storage read aborted'));
|
||||
tx.oncomplete = () => { try { resolve(request.result === undefined ? undefined : files(request.result.value)); } catch (error) { reject(error); } };
|
||||
request.onerror = () => reject(request.error);
|
||||
const request = db.transaction('setting').objectStore('setting').get(KEY);
|
||||
request.onsuccess = () => { const row = request.result as { value?: unknown } | undefined; try { resolve(row === undefined ? undefined : files(row.value)); } catch (error) { reject(error); } };
|
||||
request.onerror = () => reject(request.error ?? new Error('Camera preset storage read failed'));
|
||||
});
|
||||
}
|
||||
function snapshot(fs: CameraPresetFS, directory: string): PresetFiles {
|
||||
@@ -48,14 +45,14 @@ function restore(fs: CameraPresetFS, directory: string, value: PresetFiles): voi
|
||||
for (const name of names) if (!wanted.has(name)) fs.unlink(`${directory}/${name}`);
|
||||
for (const file of value) fs.writeFile(`${directory}/${file.name}`, file.bytes);
|
||||
}
|
||||
async function write(db: IDBDatabase, value: PresetFiles): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction('setting', 'readwrite');
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onabort = () => reject(tx.error ?? new Error('Camera preset storage commit aborted'));
|
||||
tx.onerror = () => reject(tx.error ?? new Error('Camera preset storage commit failed'));
|
||||
tx.objectStore('setting').put({ id: KEY, value });
|
||||
async function write(db: KvDatabase, value: PresetFiles): Promise<void> {
|
||||
const tx = db.transaction('setting', 'readwrite');
|
||||
const request = tx.objectStore('setting').put({ id: KEY, value });
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
request.onsuccess = () => resolve();
|
||||
request.onerror = () => reject(request.error ?? new Error('Camera preset storage commit failed'));
|
||||
});
|
||||
await tx.done;
|
||||
}
|
||||
export async function withCameraPresets<T>(fs: CameraPresetFS, directory: string, operation?: () => T): Promise<T | undefined> {
|
||||
if (!navigator.locks) throw new Error('Camera preset persistence requires browser storage locking');
|
||||
|
||||
@@ -3,36 +3,7 @@ export const STORAGE_SCHEMA_VERSION = 7;
|
||||
|
||||
export const STORAGE_STORES = ["smoke", "project", "asset", "snapshot", "operation_log", "operation_quarantine", "setting", "lod_manifest", "simulation_manifest", "simulation_quarantine", "migration"] as const;
|
||||
|
||||
export function upgradeStorageSchema(db: IDBDatabase, transaction: IDBTransaction, oldVersion: number): void {
|
||||
if (oldVersion < 1 && !db.objectStoreNames.contains("smoke")) {
|
||||
db.createObjectStore("smoke", { keyPath: "id" });
|
||||
}
|
||||
if (oldVersion < 2) {
|
||||
if (!db.objectStoreNames.contains("project")) db.createObjectStore("project", { keyPath: "id" });
|
||||
if (!db.objectStoreNames.contains("asset")) db.createObjectStore("asset", { keyPath: "id" });
|
||||
if (!db.objectStoreNames.contains("snapshot")) db.createObjectStore("snapshot", { keyPath: "id" });
|
||||
if (!db.objectStoreNames.contains("operation_log")) db.createObjectStore("operation_log", { keyPath: "id" });
|
||||
if (!db.objectStoreNames.contains("setting")) db.createObjectStore("setting", { keyPath: "id" });
|
||||
if (!db.objectStoreNames.contains("migration")) db.createObjectStore("migration", { keyPath: "id" });
|
||||
transaction.objectStore("migration").put({ id: "schema-2", version: 2, appliedAt: new Date().toISOString() });
|
||||
}
|
||||
if (oldVersion < 3) {
|
||||
if (!db.objectStoreNames.contains("lod_manifest")) db.createObjectStore("lod_manifest", { keyPath: "id" });
|
||||
transaction.objectStore("migration").put({ id: "schema-3", version: 3, appliedAt: new Date().toISOString() });
|
||||
}
|
||||
if (oldVersion < 4) {
|
||||
transaction.objectStore("migration").put({ id: "schema-4", version: 4, appliedAt: new Date().toISOString() });
|
||||
}
|
||||
if (oldVersion < 5) {
|
||||
if (!db.objectStoreNames.contains("operation_quarantine")) db.createObjectStore("operation_quarantine", { keyPath: "id" });
|
||||
transaction.objectStore("migration").put({ id: "schema-5", version: 5, appliedAt: new Date().toISOString() });
|
||||
}
|
||||
if (oldVersion < 6) {
|
||||
if (!db.objectStoreNames.contains("simulation_manifest")) db.createObjectStore("simulation_manifest", { keyPath: "id" });
|
||||
transaction.objectStore("migration").put({ id: "schema-6", version: 6, appliedAt: new Date().toISOString() });
|
||||
}
|
||||
if (oldVersion < 7) {
|
||||
if (!db.objectStoreNames.contains("simulation_quarantine")) db.createObjectStore("simulation_quarantine", { keyPath: "id" });
|
||||
transaction.objectStore("migration").put({ id: "schema-7", version: 7, appliedAt: new Date().toISOString() });
|
||||
}
|
||||
}
|
||||
// The store list above is the whole schema. OPFS KV databases have no version
|
||||
// header and no upgrade event, so there is no schema-upgrade function here: a
|
||||
// store that a build needs is simply listed in `STORAGE_STORES`, and a store
|
||||
// that is dropped stops appearing in `info().stores`.
|
||||
|
||||
78
web/app/src/storage/native-resources-opfs.ts
Normal file
78
web/app/src/storage/native-resources-opfs.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Native workflow resource archives, one file per project, in OPFS.
|
||||
*
|
||||
* This replaces the `blender-native-resources` IndexedDB database. An archive
|
||||
* is a multi-hundred-megabyte Blob, so it is stored as one OPFS file per
|
||||
* project rather than as a row in the metadata KV store: reading a single
|
||||
* project must not decode every other project's archive.
|
||||
*
|
||||
* File layout: `<root>/_kv_v1/blender-native-resources/projects/<id>.bin`
|
||||
* `[u32 headerLength][JSON header {sha256}][archive bytes…]`
|
||||
*/
|
||||
const ROOT = "_kv_v1";
|
||||
const DATABASE = "blender-native-resources";
|
||||
const STORE = "projects";
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
export interface StoredNativeResourceArchive {
|
||||
archive: Blob;
|
||||
sha256: string;
|
||||
}
|
||||
|
||||
function validateProject(project: string): string {
|
||||
if (!project || project.length > 255 || /[/\\\u0000-\u001f]/.test(project)) throw new Error("Native resource project id is invalid"); // eslint-disable-line no-control-regex -- Reject control characters in paths.
|
||||
return project;
|
||||
}
|
||||
|
||||
async function directory(create: boolean): Promise<FileSystemDirectoryHandle | undefined> {
|
||||
const storage = typeof navigator === "undefined" ? undefined : navigator.storage;
|
||||
if (!storage || typeof storage.getDirectory !== "function") throw new Error("Native resource storage requires OPFS, which is unavailable in this browser");
|
||||
let current = await storage.getDirectory();
|
||||
for (const segment of [ROOT, DATABASE, STORE]) {
|
||||
try { current = await current.getDirectoryHandle(segment, { create }); }
|
||||
catch (error) { if (!create && error instanceof DOMException && error.name === "NotFoundError") return undefined; throw error; }
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
async function fileFor(project: string): Promise<FileSystemFileHandle | undefined> {
|
||||
const store = await directory(false);
|
||||
if (!store) return undefined;
|
||||
try { return await store.getFileHandle(`${encodeURIComponent(validateProject(project))}.bin`); }
|
||||
catch (error) { if (error instanceof DOMException && error.name === "NotFoundError") return undefined; throw error; }
|
||||
}
|
||||
|
||||
export async function readNativeResourceArchive(project: string): Promise<StoredNativeResourceArchive | undefined> {
|
||||
const handle = await fileFor(project);
|
||||
if (!handle) return undefined;
|
||||
const bytes = new Uint8Array(await (await handle.getFile()).arrayBuffer());
|
||||
if (bytes.byteLength < 4) throw new Error("Native resource archive is truncated");
|
||||
const headerLength = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0, true);
|
||||
if (4 + headerLength > bytes.byteLength) throw new Error("Native resource archive header is truncated");
|
||||
const header = JSON.parse(decoder.decode(bytes.subarray(4, 4 + headerLength))) as { sha256?: unknown };
|
||||
if (typeof header.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(header.sha256)) throw new Error("Native resource archive hash is invalid");
|
||||
const body = bytes.subarray(4 + headerLength);
|
||||
return { archive: new Blob([body.slice()], { type: "application/octet-stream" }), sha256: header.sha256 };
|
||||
}
|
||||
|
||||
export async function writeNativeResourceArchive(project: string, value: StoredNativeResourceArchive): Promise<void> {
|
||||
const store = await directory(true);
|
||||
if (!store) throw new Error("RESOURCE_STORAGE_UNAVAILABLE: OPFS is unavailable");
|
||||
const body = new Uint8Array(await value.archive.arrayBuffer());
|
||||
const header = encoder.encode(JSON.stringify({ schemaVersion: 1, sha256: value.sha256 }));
|
||||
const bytes = new Uint8Array(4 + header.byteLength + body.byteLength);
|
||||
new DataView(bytes.buffer).setUint32(0, header.byteLength, true);
|
||||
bytes.set(header, 4);
|
||||
bytes.set(body, 4 + header.byteLength);
|
||||
const handle = await store.getFileHandle(`${encodeURIComponent(validateProject(project))}.bin`, { create: true });
|
||||
const writable = await handle.createWritable();
|
||||
try { await writable.write(bytes); } finally { await writable.close(); }
|
||||
}
|
||||
|
||||
export async function removeNativeResourceArchive(project: string): Promise<void> {
|
||||
const store = await directory(false);
|
||||
if (!store) return;
|
||||
try { await store.removeEntry(`${encodeURIComponent(validateProject(project))}.bin`); }
|
||||
catch (error) { if (!(error instanceof DOMException && error.name === "NotFoundError")) throw error; }
|
||||
}
|
||||
171
web/app/src/storage/opfs-browser-fs.ts
Normal file
171
web/app/src/storage/opfs-browser-fs.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* Persist the native `/browser` tree in OPFS instead of IDBFS.
|
||||
*
|
||||
* Emscripten's `FS.syncfs` is already asynchronous, so the in-memory tree keeps
|
||||
* living on MEMFS exactly as Blender sees it and only the persistence layer
|
||||
* changes: the bytes land under `projects/_browser_fs_v1/tree/` in OPFS rather
|
||||
* than in an IndexedDB database. Mount points, paths and the `syncfs(populate)`
|
||||
* contract stay untouched, so every existing `/browser/...` consumer keeps
|
||||
* working.
|
||||
*
|
||||
* There is deliberately no IndexedDB fallback: if OPFS is unavailable the
|
||||
* caller must fail loudly, because "all files live in OPFS" is a product rule,
|
||||
* not an optimisation.
|
||||
*/
|
||||
const BROWSER_FS_PROJECT = "_browser_fs_v1";
|
||||
const TREE_DIRECTORY = "tree";
|
||||
const MANIFEST_NAME = "browser-fs-manifest.json";
|
||||
|
||||
/** The slice of Emscripten's FS this module needs. */
|
||||
export interface BrowserFSLike {
|
||||
mkdirTree(path: string, mode?: number): void;
|
||||
writeFile(path: string, bytes: Uint8Array): void;
|
||||
readdir(path: string): string[];
|
||||
readFile(path: string): Uint8Array;
|
||||
lstat(path: string): { mode: number; size: number; timestamp?: number };
|
||||
isDir(mode: number): boolean;
|
||||
isFile(mode: number): boolean;
|
||||
}
|
||||
|
||||
interface ManifestEntry {
|
||||
size: number;
|
||||
mtime: number;
|
||||
}
|
||||
|
||||
interface Manifest {
|
||||
schemaVersion: 1;
|
||||
files: Record<string, ManifestEntry>;
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
function opfsRoot(storage: StorageManager | undefined = typeof navigator === "undefined" ? undefined : navigator.storage): Promise<FileSystemDirectoryHandle> {
|
||||
if (!storage || typeof storage.getDirectory !== "function") {
|
||||
return Promise.reject(new Error("OPFS is unavailable: navigator.storage.getDirectory is missing"));
|
||||
}
|
||||
return storage.getDirectory();
|
||||
}
|
||||
|
||||
async function directoryHandle(root: FileSystemDirectoryHandle, segments: string[]): Promise<FileSystemDirectoryHandle> {
|
||||
let current = root;
|
||||
for (const segment of segments) current = await current.getDirectoryHandle(segment, { create: true });
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Split a `/browser/a/b` path into safe OPFS segments, rejecting escapes. */
|
||||
function relativeSegments(path: string): string[] {
|
||||
if (!path.startsWith("/browser/")) throw new Error(`Browser FS path must live under /browser: ${path}`);
|
||||
const segments = path.slice("/browser/".length).split("/");
|
||||
if (!segments.length || segments.some((part) => !part || part === "." || part === ".." || part.includes("\\"))) {
|
||||
throw new Error(`Browser FS path is not a safe relative path: ${path}`);
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
async function readManifest(root: FileSystemDirectoryHandle): Promise<Manifest> {
|
||||
try {
|
||||
const directory = await directoryHandle(root, [BROWSER_FS_PROJECT]);
|
||||
const handle = await directory.getFileHandle(MANIFEST_NAME);
|
||||
const parsed = JSON.parse(decoder.decode(await (await handle.getFile()).arrayBuffer())) as Manifest;
|
||||
if (parsed?.schemaVersion === 1 && parsed.files && typeof parsed.files === "object") return parsed;
|
||||
} catch { /* a missing or unreadable manifest only costs a full rewrite */ }
|
||||
return { schemaVersion: 1, files: {} };
|
||||
}
|
||||
|
||||
/**
|
||||
* Load every persisted file back into the memory tree (`syncfs(true)`).
|
||||
* Mirrors Emscripten's IDBFS populate: add and overwrite, never delete, so a
|
||||
* failed read can never destroy files a running operator already opened.
|
||||
*/
|
||||
export async function populateBrowserFS(fs: BrowserFSLike, storage?: StorageManager): Promise<number> {
|
||||
const root = await opfsRoot(storage);
|
||||
let tree: FileSystemDirectoryHandle;
|
||||
try {
|
||||
tree = await (await directoryHandle(root, [BROWSER_FS_PROJECT])).getDirectoryHandle(TREE_DIRECTORY);
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === "NotFoundError") return 0;
|
||||
throw error;
|
||||
}
|
||||
let restored = 0;
|
||||
const walk = async (directory: FileSystemDirectoryHandle, prefix: string): Promise<void> => {
|
||||
for await (const [name, handle] of (directory as unknown as { entries(): AsyncIterable<[string, FileSystemHandle]> }).entries()) {
|
||||
const path = `${prefix}/${name}`;
|
||||
if (handle.kind === "directory") { await walk(handle as FileSystemDirectoryHandle, path); continue; }
|
||||
const bytes = new Uint8Array(await (await (handle as FileSystemFileHandle).getFile()).arrayBuffer());
|
||||
fs.mkdirTree(path.slice(0, path.lastIndexOf("/")));
|
||||
fs.writeFile(path, bytes);
|
||||
restored += 1;
|
||||
}
|
||||
};
|
||||
await walk(tree, "/browser");
|
||||
return restored;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush the memory tree to OPFS (`syncfs(false)`).
|
||||
*
|
||||
* Files whose size and MEMFS timestamp match the last persisted manifest are
|
||||
* skipped, so the common case (one operator touched two files) does not rewrite
|
||||
* a whole project tree. The returned count is what was actually written.
|
||||
*/
|
||||
export async function persistBrowserFS(fs: BrowserFSLike, storage?: StorageManager): Promise<number> {
|
||||
const root = await opfsRoot(storage);
|
||||
const projectDirectory = await directoryHandle(root, [BROWSER_FS_PROJECT]);
|
||||
const tree = await directoryHandle(projectDirectory, [TREE_DIRECTORY]);
|
||||
const previous = await readManifest(root);
|
||||
const next: Record<string, ManifestEntry> = {};
|
||||
let written = 0;
|
||||
let removed = 0;
|
||||
const walk = async (directory: FileSystemDirectoryHandle, prefix: string): Promise<void> => {
|
||||
for (const name of fs.readdir(prefix)) {
|
||||
if (name === "." || name === "..") continue;
|
||||
const path = `${prefix}/${name}`;
|
||||
const stat = fs.lstat(path);
|
||||
if (fs.isDir(stat.mode)) {
|
||||
await directoryHandle(tree, relativeSegments(path));
|
||||
await walk(directory, path);
|
||||
continue;
|
||||
}
|
||||
if (!fs.isFile(stat.mode)) continue;
|
||||
const entry: ManifestEntry = { size: stat.size, mtime: stat.timestamp ?? 0 };
|
||||
next[path] = entry;
|
||||
const before = previous.files[path];
|
||||
if (before && before.size === entry.size && before.mtime === entry.mtime) continue;
|
||||
const handle = await (await directoryHandle(tree, relativeSegments(path).slice(0, -1))).getFileHandle(name, { create: true });
|
||||
const writable = await handle.createWritable();
|
||||
try {
|
||||
const bytes = fs.readFile(path);
|
||||
await writable.write(bytes.slice().buffer as ArrayBuffer);
|
||||
} finally {
|
||||
await writable.close();
|
||||
}
|
||||
written += 1;
|
||||
}
|
||||
};
|
||||
await walk(tree, "/browser");
|
||||
// Mirror IDBFS deletion semantics: a file removed inside the VM must not
|
||||
// reappear on the next populate. Without this, transient render exports pile
|
||||
// up in OPFS and come back as phantom files after a reload.
|
||||
for (const stale of Object.keys(previous.files)) {
|
||||
if (next[stale]) continue;
|
||||
try {
|
||||
const segments = relativeSegments(stale);
|
||||
const parent = await directoryHandle(tree, segments.slice(0, -1));
|
||||
await parent.removeEntry(segments[segments.length - 1]);
|
||||
removed += 1;
|
||||
} catch { /* already gone, or a directory we never tracked */ }
|
||||
}
|
||||
// `syncBrowserFS(false)` runs after every command, so the steady state must be
|
||||
// a cheap walk: only rewrite the index when the file set actually moved.
|
||||
const changed = written > 0 || removed > 0 || Object.keys(next).length !== Object.keys(previous.files).length;
|
||||
if (!changed) return written;
|
||||
const manifestHandle = await projectDirectory.getFileHandle(MANIFEST_NAME, { create: true });
|
||||
const writable = await manifestHandle.createWritable();
|
||||
try {
|
||||
await writable.write(encoder.encode(JSON.stringify({ schemaVersion: 1, files: next })));
|
||||
} finally {
|
||||
await writable.close();
|
||||
}
|
||||
return written;
|
||||
}
|
||||
382
web/app/src/storage/opfs-kv.ts
Normal file
382
web/app/src/storage/opfs-kv.ts
Normal file
@@ -0,0 +1,382 @@
|
||||
/**
|
||||
* OPFS-backed replacement for the IndexedDB metadata database.
|
||||
*
|
||||
* Project rule: every file and every piece of work state lives in OPFS, and
|
||||
* `indexedDB` may not carry it. The metadata rows (project index, snapshots,
|
||||
* operation log, asset index, LOD and simulation manifests) are the last
|
||||
* IndexedDB residents. They are read through a very small slice of the IDB
|
||||
* API — transaction → objectStore → get / getAll / put / delete / clear /
|
||||
* openCursor — so this module implements exactly that slice over OPFS files and
|
||||
* keeps the call sites untouched.
|
||||
*
|
||||
* One row is one file:
|
||||
*
|
||||
* <root>/_kv_v1/<database>/<store>/<encodeURIComponent(id)>.bin
|
||||
*
|
||||
* Each file is `[u32 headerLength][JSON header][binary chunks…]`. The JSON
|
||||
* header holds the row with every ArrayBuffer / typed array replaced by a chunk
|
||||
* index, so binary payloads survive verbatim.
|
||||
*
|
||||
* Documented limits:
|
||||
* - A transaction is not atomic across stores. Writes land per operation, so a
|
||||
* crash mid-transaction can leave a store half-updated. Every caller here
|
||||
* writes one row at a time; the multi-store writes (quarantine moves) are
|
||||
* repairable by the existing quarantine scans.
|
||||
* - `getAll()` returns rows in ascending primary-key order, matching IDB.
|
||||
*/
|
||||
const KV_ROOT = "_kv_v1";
|
||||
|
||||
export interface KvRequest {
|
||||
result?: unknown;
|
||||
error?: Error | null;
|
||||
onsuccess: ((event?: unknown) => void) | null;
|
||||
onerror: ((event?: unknown) => void) | null;
|
||||
}
|
||||
|
||||
interface KvCursor {
|
||||
value: unknown;
|
||||
update(value: unknown): void;
|
||||
delete(): void;
|
||||
continue(): void;
|
||||
}
|
||||
|
||||
export interface KvStore {
|
||||
get(key: unknown): KvRequest;
|
||||
getAll(): KvRequest;
|
||||
put(value: unknown): KvRequest;
|
||||
delete(key: unknown): KvRequest;
|
||||
clear(): KvRequest;
|
||||
openCursor(): KvRequest;
|
||||
}
|
||||
|
||||
export interface KvTransaction {
|
||||
objectStore(name: string): KvStore;
|
||||
/** Resolves when every operation queued so far has landed. */
|
||||
done: Promise<void>;
|
||||
error: Error | null;
|
||||
/** IDB lifecycle hooks: the asset-catalog modules await these, not `done`. */
|
||||
oncomplete: ((event?: unknown) => void) | null;
|
||||
onabort: ((event?: unknown) => void) | null;
|
||||
onerror: ((event?: unknown) => void) | null;
|
||||
abort(): void;
|
||||
}
|
||||
|
||||
export interface KvDatabase {
|
||||
transaction(stores: string | string[], mode?: "readonly" | "readwrite"): KvTransaction;
|
||||
objectStoreNames: { contains(name: string): boolean; readonly length: number };
|
||||
close(): void;
|
||||
}
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function request(): KvRequest & { succeed(value: unknown): void; fail(error: Error): void } {
|
||||
const self: KvRequest & { succeed(value: unknown): void; fail(error: Error): void } = {
|
||||
onsuccess: null,
|
||||
onerror: null,
|
||||
// Fire on a later microtask: every call site attaches its handlers
|
||||
// synchronously after creating the request, exactly as with real IDB.
|
||||
succeed: (value) => { queueMicrotask(() => { self.result = value; self.onsuccess?.(); }); },
|
||||
fail: (error) => { queueMicrotask(() => { self.error = error; self.onerror?.(error); }); },
|
||||
};
|
||||
return self;
|
||||
}
|
||||
|
||||
function encodeValue(value: unknown, chunks: Uint8Array[]): unknown {
|
||||
if (value instanceof ArrayBuffer) { chunks.push(new Uint8Array(value)); return { __kvBin: [chunks.length - 1, "ab"] }; }
|
||||
if (ArrayBuffer.isView(value)) { chunks.push(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)); return { __kvBin: [chunks.length - 1, "u8"] }; }
|
||||
if (Array.isArray(value)) return value.map((item) => encodeValue(item, chunks));
|
||||
if (value && typeof value === "object") {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [key, item] of Object.entries(value as Record<string, unknown>)) out[key] = encodeValue(item, chunks);
|
||||
return out;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function decodeValue(value: unknown, chunks: Uint8Array[]): unknown {
|
||||
if (Array.isArray(value)) return value.map((item) => decodeValue(item, chunks));
|
||||
if (value && typeof value === "object") {
|
||||
const tag = (value as { __kvBin?: unknown }).__kvBin;
|
||||
if (Array.isArray(tag) && tag.length === 2) {
|
||||
const bytes = chunks[Number(tag[0])];
|
||||
if (!bytes) throw new Error("OPFS KV chunk index is out of range");
|
||||
return tag[1] === "ab" ? bytes.slice().buffer : bytes.slice();
|
||||
}
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [key, item] of Object.entries(value as Record<string, unknown>)) out[key] = decodeValue(item, chunks);
|
||||
return out;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function encodeRow(value: unknown): Uint8Array {
|
||||
const chunks: Uint8Array[] = [];
|
||||
const header = encoder.encode(JSON.stringify({ value: encodeValue(value, chunks), sizes: chunks.map((chunk) => chunk.byteLength) }));
|
||||
const bytes = new Uint8Array(4 + header.byteLength + chunks.reduce((total, chunk) => total + chunk.byteLength, 0));
|
||||
new DataView(bytes.buffer).setUint32(0, header.byteLength, true);
|
||||
bytes.set(header, 4);
|
||||
let offset = 4 + header.byteLength;
|
||||
for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function decodeRow(bytes: Uint8Array): { value: unknown } {
|
||||
const headerLength = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0, true);
|
||||
const header = JSON.parse(decoder.decode(bytes.subarray(4, 4 + headerLength))) as { value: unknown; sizes: number[] };
|
||||
const chunks: Uint8Array[] = [];
|
||||
let offset = 4 + headerLength;
|
||||
for (const size of header.sizes) { chunks.push(bytes.subarray(offset, offset + size)); offset += size; }
|
||||
return { value: decodeValue(header.value, chunks) };
|
||||
}
|
||||
|
||||
async function opfsRoot(): Promise<FileSystemDirectoryHandle> {
|
||||
const storage = typeof navigator === "undefined" ? undefined : navigator.storage;
|
||||
if (!storage || typeof storage.getDirectory !== "function") throw new Error("OPFS is unavailable: navigator.storage.getDirectory is missing");
|
||||
return storage.getDirectory();
|
||||
}
|
||||
|
||||
async function directory(segments: string[], create: boolean): Promise<FileSystemDirectoryHandle> {
|
||||
let current = await opfsRoot();
|
||||
for (const segment of segments) current = await current.getDirectoryHandle(segment, { create });
|
||||
return current;
|
||||
}
|
||||
|
||||
function rowName(key: unknown): string {
|
||||
const name = encodeURIComponent(String(key));
|
||||
// An empty key would collapse to ".bin" and collide with the directory entry
|
||||
// namespace, so reject it rather than inventing a sentinel.
|
||||
if (!name) throw new Error("OPFS KV row key must not be empty");
|
||||
return `${name}.bin`;
|
||||
}
|
||||
|
||||
async function readRows(store: FileSystemDirectoryHandle): Promise<{ key: string; value: unknown }[]> {
|
||||
const rows: { key: string; value: unknown }[] = [];
|
||||
for await (const [name, handle] of (store as unknown as { entries(): AsyncIterable<[string, FileSystemHandle]> }).entries()) {
|
||||
if (handle.kind !== "file" || !name.endsWith(".bin")) continue;
|
||||
const bytes = new Uint8Array(await (await (handle as FileSystemFileHandle).getFile()).arrayBuffer());
|
||||
rows.push({ key: decodeURIComponent(name.slice(0, -".bin".length)), value: decodeRow(bytes).value });
|
||||
}
|
||||
// IDB primary-key order: numbers first in numeric order, then strings.
|
||||
const keyOf = (row: { key: string; value: unknown }) => (row.value as { id?: unknown })?.id ?? row.key;
|
||||
return rows.sort((left, right) => {
|
||||
const a = keyOf(left), b = keyOf(right);
|
||||
if (typeof a === "number" && typeof b === "number") return a - b;
|
||||
if (typeof a === "number") return -1;
|
||||
if (typeof b === "number") return 1;
|
||||
return String(a).localeCompare(String(b));
|
||||
});
|
||||
}
|
||||
|
||||
async function writeRow(store: FileSystemDirectoryHandle, key: unknown, value: unknown): Promise<void> {
|
||||
const handle = await store.getFileHandle(rowName(key), { create: true });
|
||||
const writable = await handle.createWritable();
|
||||
try { await writable.write(encodeRow(value).slice().buffer as ArrayBuffer); } finally { await writable.close(); }
|
||||
}
|
||||
|
||||
async function removeRow(store: FileSystemDirectoryHandle, key: unknown): Promise<void> {
|
||||
try { await store.removeEntry(rowName(key)); }
|
||||
catch (error) { if (!(error instanceof DOMException && error.name === "NotFoundError")) throw error; }
|
||||
}
|
||||
|
||||
export async function openKvDatabase(database: string, stores: readonly string[]): Promise<KvDatabase> {
|
||||
const known = new Set(stores);
|
||||
return {
|
||||
objectStoreNames: { contains: (name: string) => known.has(name), get length() { return known.size; } },
|
||||
// OPFS handles are opened per operation, so there is nothing to release.
|
||||
close: () => undefined,
|
||||
transaction(names, mode = "readonly") {
|
||||
const writable = mode === "readwrite";
|
||||
let tail: Promise<void> = Promise.resolve();
|
||||
let queued = 0;
|
||||
let pending = 0;
|
||||
let abortError: Error | null = null;
|
||||
let chainError: Error | null = null;
|
||||
let settledState: "pending" | "complete" | "error" = "pending";
|
||||
// IDB fires `oncomplete` once no request is pending any more; the
|
||||
// asset-catalog modules await that callback rather than a promise, so the
|
||||
// transaction has to report its own settlement.
|
||||
const fire = (): void => {
|
||||
const error = abortError ?? chainError;
|
||||
transaction.error = error;
|
||||
if (error) {
|
||||
if (!abortError) transaction.onerror?.(error);
|
||||
transaction.onabort?.(error);
|
||||
}
|
||||
else transaction.oncomplete?.();
|
||||
};
|
||||
const settle = (): void => {
|
||||
if (settledState !== "pending" || pending > 0 || queued === 0) return;
|
||||
queueMicrotask(() => {
|
||||
// A handler that ran from `onsuccess` may have queued another request
|
||||
// (read-then-write transactions do exactly that), so re-check rather
|
||||
// than committing to completion.
|
||||
if (settledState !== "pending") return;
|
||||
if (pending > 0) return;
|
||||
settledState = abortError || chainError ? "error" : "complete";
|
||||
fire();
|
||||
});
|
||||
};
|
||||
// IndexedDB auto-commits a transaction that has no request once control
|
||||
// returns to the event loop. Mirror that with a macrotask so a caller
|
||||
// awaiting an empty transaction is released instead of hanging; a request
|
||||
// queued in the meantime hands settlement to `settle()` from `enqueue`.
|
||||
setTimeout(() => {
|
||||
if (settledState !== "pending" || pending > 0 || queued > 0) return;
|
||||
const idle = abortError ?? chainError;
|
||||
settledState = idle ? "error" : "complete";
|
||||
fire();
|
||||
}, 0);
|
||||
/** Queue work in transaction order; a failure aborts the remaining queue. */
|
||||
const enqueue = (operation: () => Promise<void>): Promise<void> => {
|
||||
queued += 1;
|
||||
pending += 1;
|
||||
tail = tail.then(async () => {
|
||||
try {
|
||||
if (abortError) throw abortError;
|
||||
await operation();
|
||||
}
|
||||
finally { pending -= 1; settle(); }
|
||||
}, (error: unknown) => {
|
||||
chainError ??= error instanceof Error ? error : new Error(String(error));
|
||||
pending -= 1;
|
||||
settle();
|
||||
throw error;
|
||||
});
|
||||
return tail;
|
||||
};
|
||||
const queue = (result: KvRequest & { succeed(value: unknown): void; fail(error: Error): void }, operation: () => Promise<unknown>): KvRequest => {
|
||||
// A failed request aborts the transaction in IndexedDB unless its
|
||||
// handler calls `preventDefault()`, and no caller here does. Recording
|
||||
// the failure keeps `onabort` faithful; without it a caller awaiting
|
||||
// only `oncomplete` would treat a failed write as committed.
|
||||
void enqueue(async () => {
|
||||
try { result.succeed(await operation()); }
|
||||
catch (error) {
|
||||
const failure = error instanceof Error ? error : new Error(String(error));
|
||||
chainError ??= failure;
|
||||
result.fail(failure);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
};
|
||||
// A store directory that does not exist yet is an *empty store*, not an
|
||||
// error: IndexedDB returns undefined / [] / a null cursor for a store with
|
||||
// no rows, and the first read on a fresh profile would otherwise fail the
|
||||
// whole transaction (the caller only attaches `onsuccess`).
|
||||
const dirFor = (name: string) => directory([KV_ROOT, database, name], writable).catch((error) => {
|
||||
if (!writable && error instanceof DOMException && error.name === "NotFoundError") return null;
|
||||
throw error;
|
||||
});
|
||||
const requireWritable = (result: { fail(error: Error): void }): boolean => {
|
||||
if (writable) return true;
|
||||
result.fail(new Error("OPFS KV write attempted on a readonly transaction"));
|
||||
return false;
|
||||
};
|
||||
// `readAssetCatalogIndexedDBIndex` awaits every read request and only then
|
||||
// assigns `oncomplete`, by which time the transaction has settled. A plain
|
||||
// property would swallow the callback and hang the caller, so the three
|
||||
// lifecycle hooks replay a settlement that already happened.
|
||||
type Handler = ((event?: unknown) => void) | null;
|
||||
let oncomplete: Handler = null;
|
||||
let onabort: Handler = null;
|
||||
let onerror: Handler = null;
|
||||
const replay = (assign: (value: Handler) => void, value: Handler, matches: "complete" | "error"): void => {
|
||||
assign(value);
|
||||
if (!value || settledState !== matches) return;
|
||||
queueMicrotask(() => value(transaction.error ?? undefined));
|
||||
};
|
||||
const transaction: KvTransaction = {
|
||||
// Callers queue every operation first and only then await completion, so
|
||||
// reading `tail` at access time captures the whole transaction.
|
||||
get done() { return tail.then(() => undefined, (error) => { throw error; }); },
|
||||
error: null,
|
||||
get oncomplete() { return oncomplete; }, set oncomplete(value) { replay((next) => { oncomplete = next; }, value, "complete"); },
|
||||
get onabort() { return onabort; }, set onabort(value) { replay((next) => { onabort = next; }, value, "error"); },
|
||||
get onerror() { return onerror; }, set onerror(value) { replay((next) => { onerror = next; }, value, "error"); },
|
||||
// Writes already queued ran before the abort was requested, matching the
|
||||
// per-operation (non-atomic) contract documented at the top of the file.
|
||||
abort() { abortError ??= new Error("OPFS KV transaction aborted"); settle(); },
|
||||
objectStore(name: string): KvStore {
|
||||
if (!known.has(name)) throw new Error(`OPFS KV store does not exist: ${name}`);
|
||||
const store: KvStore = {
|
||||
get(key) {
|
||||
const result = request();
|
||||
return queue(result, async () => {
|
||||
const store = await dirFor(name);
|
||||
return store ? (await readRows(store)).find((row) => row.key === String(key))?.value : undefined;
|
||||
});
|
||||
},
|
||||
getAll() {
|
||||
const result = request();
|
||||
return queue(result, async () => {
|
||||
const store = await dirFor(name);
|
||||
return store ? (await readRows(store)).map((row) => row.value) : [];
|
||||
});
|
||||
},
|
||||
put(value) {
|
||||
const result = request();
|
||||
if (!requireWritable(result)) return result;
|
||||
return queue(result, async () => {
|
||||
const id = (value as { id?: unknown }).id;
|
||||
if (id === undefined) throw new Error(`OPFS KV row for store "${name}" has no id`);
|
||||
await writeRow((await dirFor(name))!, id, value);
|
||||
return id;
|
||||
});
|
||||
},
|
||||
delete(key) {
|
||||
const result = request();
|
||||
if (!requireWritable(result)) return result;
|
||||
return queue(result, async () => { const directory = await dirFor(name); if (directory) await removeRow(directory, key); return undefined; });
|
||||
},
|
||||
clear() {
|
||||
const result = request();
|
||||
if (!requireWritable(result)) return result;
|
||||
return queue(result, async () => {
|
||||
const storeDirectory = await dirFor(name);
|
||||
if (storeDirectory) {
|
||||
for (const row of await readRows(storeDirectory)) await removeRow(storeDirectory, (row.value as { id?: unknown })?.id ?? row.key);
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
},
|
||||
openCursor() {
|
||||
// Real cursor semantics: `onsuccess` fires once per row with a
|
||||
// cursor in `result`, and the caller advances with `continue()`
|
||||
// (or ends the walk by not calling it). `update`/`delete` act on
|
||||
// the current row. This mirrors the IDB contract the one caller
|
||||
// (the shader-resource dedup pass) was written against.
|
||||
const result = request();
|
||||
let rows: { key: string; value: unknown }[] = [];
|
||||
let store: FileSystemDirectoryHandle | null = null;
|
||||
let index = 0;
|
||||
const emit = (): void => {
|
||||
const row = rows[index];
|
||||
if (!row) { result.result = null; result.onsuccess?.(); return; }
|
||||
const cursor: KvCursor = {
|
||||
value: row.value,
|
||||
update: (next) => { void enqueue(() => store ? writeRow(store, (next as { id?: unknown })?.id ?? row.key, next) : Promise.resolve()); },
|
||||
delete: () => { void enqueue(() => store ? removeRow(store, row.key) : Promise.resolve()); },
|
||||
continue: () => { index += 1; queueMicrotask(emit); },
|
||||
};
|
||||
result.result = cursor;
|
||||
result.onsuccess?.();
|
||||
};
|
||||
void enqueue(async () => {
|
||||
try {
|
||||
store = await dirFor(name);
|
||||
rows = store ? await readRows(store) : [];
|
||||
emit();
|
||||
}
|
||||
catch (error) { result.fail(error instanceof Error ? error : new Error(String(error))); }
|
||||
});
|
||||
return result;
|
||||
},
|
||||
};
|
||||
return store;
|
||||
},
|
||||
};
|
||||
return transaction;
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user