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 publishes only into the world that asked for it

esengine1ecd50345023
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index bba569280..e7cf29aef 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -377,6 +377,9 @@ export class Assets {
* decrements, and the loader's unload runs only at zero — so an asset
* shared by two scenes survives the first scene's unload. */
private genericRefs_ = new AssetRefLedger<PreparedLoad<unknown>>();
+ /** Eras already given back, so N callers abandoning one shared load hand it
+ * over once between them rather than unloading it N times. */
+ private retired_ = new WeakSet<PreparedLoad<unknown>>();
private loadContext_: LoadContext | null = null;
private assetRefResolver_: AssetRefResolver | null = null;
private assetRegistry_: AssetRegistry | null = null;
@@ -1611,6 +1614,8 @@ export class Assets {
* preparation acquired goes back — in that order, since the value is what
* is still using it. */
private retire_(type: string, era: PreparedLoad<unknown>): void {
+ if (this.retired_.has(era)) return;
+ this.retired_.add(era);
try {
this.loaders_.get(type)?.unload?.(era.value);
} finally {
@@ -2010,9 +2015,19 @@ export class Assets {
throw new Error(`Loader for "${type}" publishes by name; acquire it through its slot`);
}
const load = loader.load.bind(loader);
+ const epoch = this.resetEpoch_;
const era = await this.genericCacheFor_(type).getOrLoad(path, () =>
this.prepared_(async (ctx) => ({ value: await load(path, ctx) as unknown })),
);
+ // BEFORE acquiring, as with textures: a realm that let go while this
+ // loaded has drained the ledger this row would go in, so nothing would
+ // ever unload it.
+ if (epoch !== this.resetEpoch_) {
+ this.retire_(type, era);
+ throw new Error(
+ `Assets were released while "${ref}" was loading; it has no owner. Load it again.`,
+ );
+ }
const lease = this.genericRefs_.acquire(`${type}:${path}`, era);
const result = era.value as T;
const handle = (result as { handle?: unknown } | null)?.handle;
diff --git a/sdk/src/asset/registryAssets.ts b/sdk/src/asset/registryAssets.ts
index 944229fda..e57f14add 100644
--- a/sdk/src/asset/registryAssets.ts
+++ b/sdk/src/asset/registryAssets.ts
@@ -61,6 +61,9 @@ class Slot<T> {
refs = 0;
era: PreparedEra<T> | null = null;
loading: Promise<PreparedEra<T>> | null = null;
+ /** Which refresh is the current one. A preparation that started before the
+ * count moved is answering a question nobody is asking any more. */
+ refresh = 0;
constructor(readonly type: string, readonly key: string, readonly id: number) {}
}
@@ -102,6 +105,13 @@ export class RegistryAssetSlots {
throw e;
}
slot.loading = null;
+ // The realm can have let go of everything while this prepared. The
+ // slot is off the table, so publishing into it would hand a lease on
+ // an era nothing resolves to and nobody will ever release.
+ if (this.byName_.get(lookupKey(type, key)) !== slot) {
+ era.dependencies.releaseAll();
+ throw new Error(`"${key}" was released while it was loading; it has no owner. Load it again.`);
+ }
// Another acquire may have published while this one awaited; joining
// it is a cache hit, and publishing twice would retire what is live.
if (!slot.era) {
@@ -118,12 +128,21 @@ export class RegistryAssetSlots {
*
* A failed prepare leaves the slot exactly as it was — holders keep working
* with the era they have rather than losing it to a bad download. Answers
- * false when nothing holds this name.
+ * false when nothing holds this name, and when what came back is no longer
+ * the answer to any live question.
*/
async republish<T>(kind: RegistryAssetKind<T>, type: string, name: string): Promise<boolean> {
const slot = this.byName_.get(lookupKey(type, name)) as Slot<T> | undefined;
if (!slot?.era) return false;
+ const ticket = ++slot.refresh;
const era = await kind.prepare(slot.key);
+ // Two things can have happened while this prepared: a newer refresh
+ // started, or the last holder let go. Publishing either way puts an era
+ // where nothing will ever release it.
+ if (ticket !== slot.refresh || !slot.era) {
+ era.dependencies.releaseAll();
+ return false;
+ }
const previous = slot.era;
slot.era = era;
// Its dependencies only: what the name resolves to is the slot's, and
diff --git a/sdk/tests/asset-dependencies.test.ts b/sdk/tests/asset-dependencies.test.ts
index 5f0442d05..3a71fa253 100644
--- a/sdk/tests/asset-dependencies.test.ts
+++ b/sdk/tests/asset-dependencies.test.ts
@@ -270,6 +270,30 @@ describe('a handle-bound load is a preparation too', () => {
expect(assets.dependenciesOf('gadget', 'x.gadget')).toEqual([]);
});
+ it('a load that lands after the realm let go has no owner to hand to', async () => {
+ // Handing it over would open a ledger row in a realm that already
+ // drained its own, and nothing would ever unload it.
+ const assets = realm({});
+ let finish = (): void => {};
+ assets.register<{ handle: number }>({
+ type: 'slow', extensions: ['.slow'],
+ load: async (_path, ctx) => {
+ const tex = await ctx.acquireTexture('g.png');
+ await new Promise<void>((resolve) => { finish = resolve; });
+ return { handle: tex.value.handle };
+ },
+ unload: () => {},
+ });
+
+ const loading = assets.acquireTyped('slow', 'x.slow');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assets.releaseAll();
+ finish();
+
+ await expect(loading).rejects.toThrow(/released while/);
+ expect(pool.liveTextures(), 'the texture the ownerless load took').toBe(0);
+ });
+
it('a load that throws keeps nothing it acquired', async () => {
const assets = realm({});
gadget(assets, { fail: true });
diff --git a/sdk/tests/registry-asset-slots.test.ts b/sdk/tests/registry-asset-slots.test.ts
index 75137e483..2933671ce 100644
--- a/sdk/tests/registry-asset-slots.test.ts
+++ b/sdk/tests/registry-asset-slots.test.ts
@@ -37,6 +37,89 @@ function fakeLease(key: string, released: string[]): AssetLease {
return lease;
}
+/** The same, with every preparation held open until the test lets it finish. */
+function gated() {
+ const released: string[] = [];
+ const pending = new Map<number, () => void>();
+ let era = 0;
+ const kind: RegistryAssetKind<{ id: string }> = {
+ prepare: async (path: string) => {
+ const name = `${path}#${++era}`;
+ await new Promise<void>((resolve) => pending.set(era, resolve));
+ const dependencies = new AssetScope();
+ dependencies.add(fakeLease(`${name}:texture`, released));
+ return { published: { name }, value: { id: path }, dependencies, edges: [] };
+ },
+ };
+ /** Let preparation `n` finish, once whatever starts it has had its turn. */
+ const finish = async (n: number): Promise<void> => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ pending.get(n)!();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ };
+ return { released, kind, finish };
+}
+
+describe('a refresh publishes only if it is still the current one', () => {
+ it('a preparation that started earlier cannot land on top of a newer one', async () => {
+ // Two updates in flight is what propagation makes ordinary: a change to
+ // one texture re-prepares every parent that took it, twice in a row if
+ // the file is saved twice. Whichever finishes last would win.
+ const { released, kind, finish } = gated();
+ const slots = new RegistryAssetSlots();
+ const acquiring = slots.acquire(kind, 'anim-clip', 'walk.esanim', ['walk.esanim']);
+ await finish(1);
+ await acquiring;
+
+ const older = slots.republish(kind, 'anim-clip', 'walk.esanim');
+ const newer = slots.republish(kind, 'anim-clip', 'walk.esanim');
+ await finish(3);
+ expect(await newer).toBe(true);
+ await finish(2);
+
+ expect(await older, 'the stale preparation published itself').toBe(false);
+ expect(slots.published('anim-clip', 'walk.esanim')).toEqual({ name: 'walk.esanim#3' });
+ expect(released, 'the stale era kept what it had acquired')
+ .toContain('walk.esanim#2:texture');
+ });
+
+ it('an acquire that lands after the realm let go has no owner to hand to', async () => {
+ // Publishing it would put an era under a name the realm no longer keeps,
+ // and hand a lease on it to a caller whose world is already gone. The
+ // texture path answers a teardown-during-load the same way.
+ const { released, kind, finish } = gated();
+ const slots = new RegistryAssetSlots();
+ const acquiring = slots.acquire(kind, 'anim-clip', 'walk.esanim', ['walk.esanim']);
+
+ slots.releaseAll();
+ await finish(1);
+
+ await expect(acquiring).rejects.toThrow(/released while it was loading/);
+ expect(released, 'the era nobody could own kept what it took')
+ .toEqual(['walk.esanim#1:texture']);
+ expect(slots.size).toBe(0);
+ });
+
+ it('a slot whose last holder left while it prepared stays gone', async () => {
+ // Publishing into it would put an era under a name nothing resolves to
+ // any more: no holder can ever release it, so nothing it took comes back.
+ const { released, kind, finish } = gated();
+ const slots = new RegistryAssetSlots();
+ const acquiring = slots.acquire(kind, 'anim-clip', 'walk.esanim', ['walk.esanim']);
+ await finish(1);
+ const held = await acquiring;
+
+ const refresh = slots.republish(kind, 'anim-clip', 'walk.esanim');
+ held.release();
+ await finish(2);
+
+ expect(await refresh).toBe(false);
+ expect(slots.size).toBe(0);
+ expect(slots.published('anim-clip', 'walk.esanim')).toBeUndefined();
+ expect(released).toEqual(['walk.esanim#1:texture', 'walk.esanim#2:texture']);
+ });
+});
+
describe('a ref-bound asset is owned as a slot', () => {
it('the last holder takes the publication and its dependencies with it', async () => {
// The permanent pin this replaces: nothing released a registry-backed