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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(sdk): AsyncCache releases loads that finish after a timeout (audit A17)
esengine50ba541f560b
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 8c96ffa58..ac8ccd987 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -139,7 +139,11 @@ export class Assets {private textureImportResolver_: TextureImportSettingsResolver | null = null;private spineLoader_: SpineAssetLoader;- private textureCache_ = new AsyncCache<TextureResult>();+ private textureCache_ = new AsyncCache<TextureResult>((result) => {+ // A texture whose load finished after its getOrLoad timed out has no+ // owner; release its GL handle so it doesn't leak VRAM (audit A17).+ requireResourceManager().releaseTexture(result.handle);+ });private textureRefCounts_ = new Map<string, number>();private genericCache_ = new Map<string, AsyncCache<unknown>>();private loadContext_: LoadContext | null = null;diff --git a/sdk/src/asset/AsyncCache.ts b/sdk/src/asset/AsyncCache.tsindex 7eafee273..d6a5b1440 100644--- a/sdk/src/asset/AsyncCache.ts+++ b/sdk/src/asset/AsyncCache.ts@@ -16,6 +16,15 @@ export class AsyncCache<T> {private pending_ = new Map<string, PendingEntry<T>>();private failed_ = new Map<string, FailedEntry>();+ /**+ * @param dispose_ Optional releaser for a value whose load finishes AFTER+ * its getOrLoad already timed out — the caller got the timeout rejection,+ * so that late value has no owner and would otherwise leak (e.g. a GL+ * texture created past the deadline; audit A17). NOT called for+ * invalidate()/clearAll(), whose in-flight results still reach the caller.+ */+ constructor(private dispose_?: (value: T) => void) {}+async getOrLoad(key: string, loader: () => Promise<T>, timeout = RuntimeConfig.assetLoadTimeout): Promise<T> {const cached = this.cache_.get(key);if (cached !== undefined) {@@ -38,21 +47,38 @@ export class AsyncCache<T> {entry.promise = (async () => {const loaderPromise = loader();- const result = await (timeout > 0- ? Promise.race([- loaderPromise,- new Promise<never>((_, reject) =>- setTimeout(() => {- entry.aborted = true;- reject(new Error(`AsyncCache timeout: ${key} (${timeout}ms)`));- }, timeout)- ),- ])- : loaderPromise);-- if (!entry.aborted) {- this.cache_.set(key, result);+ if (timeout <= 0) {+ const result = await loaderPromise;+ if (!entry.aborted) this.cache_.set(key, result);+ this.pending_.delete(key);+ return result;}++ let timedOut = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ // The loader keeps running even when the deadline wins the race. If+ // it produces a value after timing out, that value has no owner —+ // release it so it doesn't leak (audit A17).+ void loaderPromise.then(+ (late) => { if (timedOut) this.disposeAbandoned_(key, late); },+ () => { /* loader rejected — nothing to release */ },+ );++ const result = await Promise.race([+ loaderPromise,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ timedOut = true;+ entry.aborted = true;+ reject(new Error(`AsyncCache timeout: ${key} (${timeout}ms)`));+ }, timeout);+ }),+ ]);++ // Loader won the race: cancel the deadline so it can't abort after+ // the fact, then cache (unless invalidate() aborted it in-flight).+ clearTimeout(timer);+ if (!entry.aborted) this.cache_.set(key, result);this.pending_.delete(key);return result;})();@@ -73,6 +99,16 @@ export class AsyncCache<T> {}}+ /** Release a value that was abandoned by a timeout; never throws upward. */+ private disposeAbandoned_(key: string, value: T): void {+ if (!this.dispose_) return;+ try {+ this.dispose_(value);+ } catch (e) {+ log.warn('asset', `AsyncCache: releasing abandoned "${key}" threw`, e);+ }+ }+get(key: string): T | undefined {return this.cache_.get(key);}diff --git a/sdk/tests/async-cache-leak.test.ts b/sdk/tests/async-cache-leak.test.tsnew file mode 100644index 000000000..66c9975ca--- /dev/null+++ b/sdk/tests/async-cache-leak.test.ts@@ -0,0 +1,59 @@+/**+ * @file async-cache-leak.test.ts+ * @brief Regression net for audit A17 — when a load times out, the loader+ * keeps running; its late result used to be dropped on the floor (the+ * caller already got the timeout rejection), leaking whatever it had+ * allocated (e.g. a GL texture = VRAM). AsyncCache now releases such+ * abandoned values via an optional disposer.+ */+import { describe, expect, it } from 'vitest';+import { AsyncCache } from '../src/asset/AsyncCache';++const after = (ms: number) => new Promise((r) => setTimeout(r, ms));++describe('AsyncCache abandoned-load disposal (A17)', () => {+ it('disposes a value whose load finishes AFTER the timeout', async () => {+ const disposed: number[] = [];+ const cache = new AsyncCache<number>((v) => disposed.push(v));+ const LATE = 42;+ const loader = () => new Promise<number>((res) => setTimeout(() => res(LATE), 40));++ await expect(cache.getOrLoad('k', loader, 10)).rejects.toThrow(/AsyncCache timeout/);+ expect(disposed).toEqual([]); // loader still in flight++ await after(60); // let the loader resolve past its (abandoned) deadline+ expect(disposed).toEqual([LATE]); // released, not leaked+ expect(cache.has('k')).toBe(false); // and never cached+ });++ it('caches and does NOT dispose when the load beats the timeout', async () => {+ const disposed: number[] = [];+ const cache = new AsyncCache<number>((v) => disposed.push(v));++ const result = await cache.getOrLoad('k', () => Promise.resolve(7), 1000);++ expect(result).toBe(7);+ expect(cache.get('k')).toBe(7);+ await after(5);+ expect(disposed).toEqual([]);+ });++ it('does not dispose (or surface an unhandled rejection) when the loader fails late', async () => {+ const disposed: number[] = [];+ const cache = new AsyncCache<number>((v) => disposed.push(v));+ const loader = () => new Promise<number>((_, rej) => setTimeout(() => rej(new Error('late fail')), 40));++ await expect(cache.getOrLoad('k', loader, 10)).rejects.toThrow(/AsyncCache timeout/);+ await after(60); // the late loader rejection must be swallowed, nothing released+ expect(disposed).toEqual([]);+ });++ it('works without a disposer (no-op release, still no caching of the abandoned value)', async () => {+ const cache = new AsyncCache<number>(); // no disposer+ const loader = () => new Promise<number>((res) => setTimeout(() => res(1), 40));++ await expect(cache.getOrLoad('k', loader, 10)).rejects.toThrow(/AsyncCache timeout/);+ await after(60);+ expect(cache.has('k')).toBe(false);+ });+});