Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(assets): a preparation that fails may not keep what it took

esenginec119cdd40cee
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index d871abdcd..bdc7599cf 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -22,7 +22,7 @@ import { AssetRefLedger, type AssetRefLease } from './AssetRefLedger';
import { AssetScope, type AssetLease } from './AssetLease';
import { EntityAssetScopes } from './entityAssetScopes';
import { RegistryAssetSlots, type RegistryAssetKind } from './registryAssets';
-import { DependencyRecorder, type DependencyReceipt } from './dependencies';
+import { DependencyRecorder, type DependencyReceipt, type Preparation } from './dependencies';
import { SpineAssetLoader } from './loaders/SpineAssetLoader';
import { MaterialAssetLoader } from './loaders/MaterialAssetLoader';
import { MeshAssetLoader } from './loaders/MeshAssetLoader';
@@ -2059,16 +2059,25 @@ export class Assets {
const loader = this.loaders_.get(type) as AssetLoader<T> | undefined;
const registry = loader?.registry;
if (!registry) return null;
- return {
- prepare: async (path) => {
- // One recorder per preparation: what the loader takes IS the
- // era's ownership and IS the graph's edges, so neither can be
- // a description it forgot to keep in step with its work.
- const recorder = new DependencyRecorder();
- const era = await registry.prepare(path, this.recordingContext_(recorder));
- return { ...era, dependencies: recorder.acquired, edges: recorder.edges };
- },
- };
+ return { prepare: (path) => this.prepared_((ctx) => registry.prepare(path, ctx)) };
+ }
+
+ /**
+ * Run one preparation: what the loader takes IS the result's ownership and
+ * IS the graph's edges. A transaction, because an acquisition on the way to
+ * a value that never arrives has no owner — the thing that would have held
+ * it does not exist.
+ */
+ private async prepared_<T extends object>(
+ work: (ctx: LoadContext) => Promise<T>,
+ ): Promise<T & Preparation> {
+ const recorder = new DependencyRecorder();
+ try {
+ return recorder.commit(await work(this.recordingContext_(recorder)));
+ } catch (e) {
+ recorder.rollback();
+ throw e;
+ }
}
/** The load context one preparation sees: every door that takes something
diff --git a/sdk/src/asset/dependencies.ts b/sdk/src/asset/dependencies.ts
index 61c1a24d1..1416fe9ab 100644
--- a/sdk/src/asset/dependencies.ts
+++ b/sdk/src/asset/dependencies.ts
@@ -32,6 +32,7 @@
*/
import type { AssetLease } from './AssetLease';
import { AssetScope } from './AssetLease';
+import { log } from '../util/logger';
export type DependencyKind = 'owned' | 'source';
@@ -45,29 +46,73 @@ export interface DependencyReceipt {
readonly path: string;
}
+/** What one preparation took, sealed onto what it produced. */
+export interface Preparation {
+ /** Everything it acquired; released when what it produced retires. */
+ readonly dependencies: AssetScope;
+ /** Every edge it produced, owned and source alike. */
+ readonly edges: readonly DependencyReceipt[];
+}
+
/**
* The recorder behind one preparation: everything it acquires lands here, so
* neither the era's ownership nor the graph's edges depend on a loader
* remembering to report anything.
+ *
+ * It is also the preparation's TRANSACTION. An acquisition made on the way to a
+ * value that never arrives has no owner — the era that would have held it does
+ * not exist, and no caller was ever handed a receipt for it — so a preparation
+ * either commits what it took onto what it produced, or gives all of it back.
*/
export class DependencyRecorder {
private readonly edges_: DependencyReceipt[] = [];
- readonly acquired = new AssetScope();
+ private readonly acquired_ = new AssetScope();
+ private state_: 'open' | 'committed' | 'rolled-back' = 'open';
/** A runtime resource this preparation now holds. */
own<T>(path: string, lease: AssetLease<T>, type?: string): AssetLease<T> {
- this.acquired.add(lease);
+ if (this.state_ !== 'open') return this.late_(lease);
+ this.acquired_.add(lease);
this.edges_.push(type === undefined ? { kind: 'owned', path } : { kind: 'owned', type, path });
return lease;
}
/** Content this preparation read to decide what to produce. */
read(path: string): void {
+ if (this.state_ !== 'open') return;
this.edges_.push({ kind: 'source', path });
}
- /** What this preparation took, in the order it took it. */
- get edges(): readonly DependencyReceipt[] {
- return this.edges_;
+ /**
+ * The preparation produced `value`: what it took is what that value owns.
+ *
+ * Sealing here rather than at the call site is what makes the two
+ * inseparable — there is no shape of the result that carries edges without
+ * the receipts behind them.
+ */
+ commit<T extends object>(value: T): T & Preparation {
+ this.state_ = 'committed';
+ return { ...value, dependencies: this.acquired_, edges: this.edges_ };
+ }
+
+ /** The preparation produced nothing, so it may keep nothing. */
+ rollback(): void {
+ this.state_ = 'rolled-back';
+ this.acquired_.releaseAll();
+ this.edges_.length = 0;
+ }
+
+ /**
+ * An acquisition that landed after the transaction settled: the losing half
+ * of a preparation whose other half threw, or a loader that kept the context
+ * past its own work. Nobody can own it either way, so it goes back here —
+ * the last place that still knows it exists.
+ */
+ private late_<T>(lease: AssetLease<T>): AssetLease<T> {
+ if (this.state_ === 'committed') {
+ log.warn('asset', `an acquisition of "${lease.key}" landed after its preparation was published`);
+ }
+ lease.release();
+ return lease;
}
}
diff --git a/sdk/src/asset/registryAssets.ts b/sdk/src/asset/registryAssets.ts
index 2fc8c26a8..944229fda 100644
--- a/sdk/src/asset/registryAssets.ts
+++ b/sdk/src/asset/registryAssets.ts
@@ -23,8 +23,7 @@
* today that is only prevented by the file extensions differing.
*/
import type { AssetLease } from './AssetLease';
-import type { DependencyReceipt } from './dependencies';
-import { AssetScope } from './AssetLease';
+import type { DependencyReceipt, Preparation } from './dependencies';
/** What one preparation PRODUCED. What it took is recorded for it — see
* dependencies.ts — so an era cannot describe a dependency it does not have. */
@@ -36,12 +35,7 @@ export interface RegistryEra<T> {
}
/** One era, with what its preparation took. */
-export interface PreparedEra<T> extends RegistryEra<T> {
- /** What this era acquired for itself; released when it retires. */
- readonly dependencies: AssetScope;
- /** Every edge the preparation produced, owned and source alike. */
- readonly edges: readonly DependencyReceipt[];
-}
+export type PreparedEra<T> = RegistryEra<T> & Preparation;
/** How one kind of registry-backed asset is prepared. Publishing is the slot's:
* it holds the era and answers the lookup, so there is nowhere else to write. */
diff --git a/sdk/tests/asset-dependencies.test.ts b/sdk/tests/asset-dependencies.test.ts
index 185cb1571..69bd1a35f 100644
--- a/sdk/tests/asset-dependencies.test.ts
+++ b/sdk/tests/asset-dependencies.test.ts
@@ -161,3 +161,46 @@ describe('an edge comes from the acquisition that made it', () => {
'one realm\'s edges showed up in the other').toBe(false);
});
});
+
+describe('a preparation is a transaction', () => {
+ beforeEach(() => { pool = createPoolFake(); });
+
+ /** A registry-backed loader that takes two textures and then fails. */
+ function brittle(assets: Assets): void {
+ assets.register({
+ type: 'brittle',
+ extensions: ['.brittle'],
+ registry: {
+ prepare: async (_path, ctx) => {
+ await ctx.acquireTexture('a.png');
+ await ctx.acquireTexture('b.png');
+ throw new Error('prepare failed');
+ },
+ },
+ });
+ }
+
+ it('a preparation that throws keeps nothing it acquired', async () => {
+ // Nothing took over the receipts: there is no era to hold them, and the
+ // slot the acquire was for is gone. Only the attempt itself knows what
+ // it took, so only the attempt can give it back.
+ const assets = realm({});
+ brittle(assets);
+ const base = assets.sizes().refRows;
+
+ await expect(assets.acquireTyped('brittle', 'x.brittle')).rejects.toThrow('prepare failed');
+
+ expect(pool.liveTextures(), 'the textures the failed attempt took').toBe(0);
+ expect(assets.sizes().refRows, 'the ledger rows it opened').toBe(base);
+ });
+
+ it('a failed preparation publishes nothing and leaves no edges', async () => {
+ const assets = realm({});
+ brittle(assets);
+
+ await expect(assets.acquireTyped('brittle', 'x.brittle')).rejects.toThrow();
+
+ expect(assets.dependenciesOf('brittle', 'x.brittle')).toEqual([]);
+ expect(assets.resolveRegistryAsset('brittle', 'x.brittle')).toBeUndefined();
+ });
+});