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
feat(platform): content-addressed disk cache for offline hot-update
yhh64ded4234ac7
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex cc9f05bc3..2a596bdce 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -4441,10 +4441,12 @@ name: "web" | "wechat" | "douyin" | "node" | "native"now: () => numberonMemoryWarning: ((callback: () => void) => () => void) | undefinedpollGamepads: (() => GamepadSnapshot[]) | undefined+readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefinedreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>removeStorageItem: (key: string) => voidsetStorageItem: (key: string, value: string) => void+writeCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```## PlatformAudioBackend — interfacediff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex a275e661f..375c916a2 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -4436,10 +4436,12 @@ name: "web" | "wechat" | "douyin" | "node" | "native"now: () => numberonMemoryWarning: ((callback: () => void) => () => void) | undefinedpollGamepads: (() => GamepadSnapshot[]) | undefined+readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefinedreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>removeStorageItem: (key: string) => voidsetStorageItem: (key: string, value: string) => void+writeCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```## PlatformAudioBackend — interfacediff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 31656084a..f61b51fab 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -4443,10 +4443,12 @@ name: "web" | "wechat" | "douyin" | "node" | "native"now: () => numberonMemoryWarning: ((callback: () => void) => () => void) | undefinedpollGamepads: (() => GamepadSnapshot[]) | undefined+readCacheFile: ((key: string) => Promise<ArrayBuffer | null>) | undefinedreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>removeStorageItem: (key: string) => voidsetStorageItem: (key: string, value: string) => void+writeCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```## PlatformAudioBackend — interfacediff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex d37c1c4a9..4435c0e83 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -5,7 +5,7 @@ import { Catalog, type AtlasFrameInfo } from './Catalog';import { ManifestModel, normalizeBundleMode, type AddressableManifest } from './AddressableManifest';import { diffManifests, type UpdatePlan, type AssetChange } from './hotUpdate';import { contentHashHex } from './contentHash';-import { platformLoadSubpackage, platformGetStorageItem, platformSetStorageItem } from '../platform';+import { platformLoadSubpackage, platformGetStorageItem, platformSetStorageItem, platformWriteCacheFile } from '../platform';import type {AssetLoader, LoadContext, TextureResult, SpineResult,MaterialResult, FontResult, AudioResult, AnimClipResult,@@ -693,10 +693,16 @@ export class Assets {const remote = group != null && normalizeBundleMode(group.bundleMode) === 'remote';const path = remote ? this.remoteUrlFor_(c.path, root) : this.resolveLoadPath_(c.path);try {- const buf = await this.backend.fetchBinary(this.backend.resolveUrl(path));+ const url = this.backend.resolveUrl(path);+ const buf = await this.backend.fetchBinary(url);if (c.contentHash && contentHashHex(new Uint8Array(buf)) !== c.contentHash) {return 'integrity';}+ // Persist the verified, content-addressed bytes to the disk cache (keyed by+ // the immutable CDN url) so they load offline on the next boot and skip the+ // CDN. Best-effort (no-op on platforms without a cache, e.g. web); a failed+ // write never fails the update.+ if (remote) await platformWriteCacheFile(url, buf);return null;} catch {return 'fetch';diff --git a/sdk/src/asset/Backend.ts b/sdk/src/asset/Backend.tsindex 8b5f8a841..032a3d358 100644--- a/sdk/src/asset/Backend.ts+++ b/sdk/src/asset/Backend.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { platformFetch, platformReadFile, platformReadTextFile } from '../platform';+import { platformFetch, platformReadFile, platformReadTextFile, platformReadCacheFile } from '../platform';export interface Backend {fetchBinary(path: string): Promise<ArrayBuffer>;@@ -22,6 +22,15 @@ export class HttpBackend implements Backend {async fetchBinary(path: string): Promise<ArrayBuffer> {const url = this.resolveUrl(path);+ // Content cache: hot-update wrote its verified, content-addressed (immutable)+ // assets to the platform's disk store keyed by this url; serve them first so+ // updated assets load offline and skip the CDN roundtrip. Only remote (http(s))+ // urls are cache-eligible — local / same-origin paths are already local, and+ // nothing else is ever written, so a miss just falls through to a normal fetch.+ if (/^https?:\/\//i.test(url)) {+ const cached = await platformReadCacheFile(url);+ if (cached) return cached;+ }const response = await platformFetch(url);if (!response.ok) {throw new Error(`Failed to fetch '${path}': ${response.status} ${response.statusText}`);diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsindex 45f6f7c38..8fa1fd4bf 100644--- a/sdk/src/platform/base.ts+++ b/sdk/src/platform/base.ts@@ -144,6 +144,35 @@ export function platformLoadSubpackage(name: string): Promise<void> {return p.loadSubpackage ? p.loadSubpackage(name) : Promise.resolve();}+/** Read a content-addressed asset from the persistent cache (hot-update's offline+ * store). Returns null on a miss, when the platform has no cache (web), when the+ * platform is uninitialized (tests), OR on any read error — every case means "not+ * cached, fetch normally", so cache failures never break loading. */+export async function platformReadCacheFile(key: string): Promise<ArrayBuffer | null> {+ if (!isPlatformInitialized()) return null;+ const p = getPlatform();+ if (!p.readCacheFile) return null;+ try {+ return await p.readCacheFile(key);+ } catch {+ return null;+ }+}++/** Persist a content-addressed asset to the cache. No-op when the platform has no+ * cache (web) or is uninitialized (tests); swallows write errors (best-effort — a+ * failed cache write must not fail the update). */+export async function platformWriteCacheFile(key: string, bytes: ArrayBuffer): Promise<void> {+ if (!isPlatformInitialized()) return;+ const p = getPlatform();+ if (!p.writeCacheFile) return;+ try {+ await p.writeCacheFile(key, bytes);+ } catch {+ // best-effort cache; ignore+ }+}+/** Subscribe to OS memory-pressure warnings (wx.onMemoryWarning on WeChat).* Returns an unsubscribe. On platforms without a pressure signal the callback* simply never fires. Tolerates an uninitialized platform (tests). */diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.tsindex 6634d5dbb..be1021878 100644--- a/sdk/src/platform/index.ts+++ b/sdk/src/platform/index.ts@@ -39,6 +39,8 @@ export {platformNow,platformCreateAudioBackend,platformLoadSubpackage,+ platformReadCacheFile,+ platformWriteCacheFile,platformOnMemoryWarning,platformGetStorageItem,platformSetStorageItem,diff --git a/sdk/src/platform/native/adapter.ts b/sdk/src/platform/native/adapter.tsindex 055bbcef9..e580c5ab7 100644--- a/sdk/src/platform/native/adapter.ts+++ b/sdk/src/platform/native/adapter.ts@@ -169,6 +169,17 @@ export class NativePlatformAdapter implements PlatformAdapter {}}+ // Content-addressed disk cache — delegates to the shell's on-disk store when it+ // provides one, else behaves as "no cache" (miss / no-op), so hot-update degrades+ // to plain CDN refetch on a shell without caching.+ async readCacheFile(key: string): Promise<ArrayBuffer | null> {+ return this.bridge_.readCacheFile ? this.bridge_.readCacheFile(key) : null;+ }++ async writeCacheFile(key: string, bytes: ArrayBuffer): Promise<void> {+ if (this.bridge_.writeCacheFile) await this.bridge_.writeCacheFile(key, bytes);+ }+// createSocket / createVideoBackend / pollGamepads / loadSubpackage /// onMemoryWarning are optional and deferred to the shell.}diff --git a/sdk/src/platform/native/bridge.ts b/sdk/src/platform/native/bridge.tsindex a1eb1432a..8f02ea6f4 100644--- a/sdk/src/platform/native/bridge.ts+++ b/sdk/src/platform/native/bridge.ts@@ -74,6 +74,13 @@ export interface NativeBridge {removeStorageItem(key: string): void;storageKeys(): string[];+ /** Persistent content-addressed byte cache (hot-update offline store): the shell+ * writes verified downloaded assets to disk and reads them back. Optional — a+ * shell without on-disk caching omits both, and hot-updated assets simply refetch+ * from the CDN. See {@link PlatformAdapter.readCacheFile}. */+ readCacheFile?(key: string): Promise<ArrayBuffer | null>;+ writeCacheFile?(key: string, bytes: ArrayBuffer): Promise<void>;+/** Register the engine's input sink; returns an unsubscribe. */registerInput(listener: NativeInputListener): () => void;diff --git a/sdk/src/platform/node.ts b/sdk/src/platform/node.tsindex 7fcc12645..93d6d3da6 100644--- a/sdk/src/platform/node.ts+++ b/sdk/src/platform/node.ts@@ -11,7 +11,10 @@** @beta Pre-1.0: the node/headless host is young; the adapter surface may change.*/-import { readFile as fsReadFile, access } from 'node:fs/promises';+import { readFile as fsReadFile, access, mkdir, writeFile, rename } from 'node:fs/promises';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { createHash } from 'node:crypto';import type {PlatformAdapter,PlatformRequestOptions,@@ -162,6 +165,38 @@ class NodePlatformAdapter implements PlatformAdapter {if (k.startsWith(prefix)) this.storage_.delete(k);}}++ // Content-addressed disk cache (hot-update offline store). Dir defaults to the+ // OS temp dir; override with ESENGINE_CACHE_DIR. The key is a content-addressed+ // url — an immutable name — so the filename is just its sha256 (filesystem-safe,+ // collision-resistant).+ private cacheDir_(): string {+ return process.env.ESENGINE_CACHE_DIR ?? join(tmpdir(), 'esengine-cache');+ }++ private cacheFile_(key: string): string {+ return join(this.cacheDir_(), createHash('sha256').update(key).digest('hex'));+ }++ async readCacheFile(key: string): Promise<ArrayBuffer | null> {+ try {+ const buf = await fsReadFile(this.cacheFile_(key));+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer;+ } catch {+ return null; // ENOENT ⇒ not cached+ }+ }++ async writeCacheFile(key: string, bytes: ArrayBuffer): Promise<void> {+ const dir = this.cacheDir_();+ await mkdir(dir, { recursive: true });+ // Write to a temp file then rename: a crash mid-write must never leave a+ // truncated file that a later content-addressed read would trust as complete.+ const file = this.cacheFile_(key);+ const tmp = `${file}.${process.pid}.tmp`;+ await writeFile(tmp, new Uint8Array(bytes));+ await rename(tmp, file);+ }}export const nodeAdapter = new NodePlatformAdapter();diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex 30ede0de8..973469e72 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -282,6 +282,21 @@ export interface PlatformAdapter {* concept (web) omit it and lazy groups load directly from their URLs. */loadSubpackage?(name: string): Promise<void>;+ /**+ * Persistent content-addressed byte cache — the offline/disk primitive behind+ * hot-update. `key` is an immutable content-addressed url (the asset's `<hash>.<ext>`+ * CDN url), so an entry NEVER goes stale and needs no invalidation. Hot-update+ * writes each verified downloaded asset here; the http backend reads it first so+ * updated assets stay available offline and skip the CDN roundtrip.+ *+ * Optional — a platform with no local storage (web relies on the browser HTTP+ * cache) omits BOTH; then `platformReadCacheFile` returns null (a miss → normal+ * fetch) and `platformWriteCacheFile` is a no-op. Node (fs) and native (the shell's+ * on-disk store) implement them; WeChat may later back them with `wx` user storage.+ */+ readCacheFile?(key: string): Promise<ArrayBuffer | null>;+ writeCacheFile?(key: string, bytes: ArrayBuffer): Promise<void>;+/** Open a socket connection. Web → WebSocket, WeChat → wx.connectSocket,* Node → a ws wrapper. Optional — platforms without networking (playable* ads) omit it and `createSocket()` fails loud. */diff --git a/sdk/tests/content-cache.test.ts b/sdk/tests/content-cache.test.tsnew file mode 100644index 000000000..d2f5cefac--- /dev/null+++ b/sdk/tests/content-cache.test.ts@@ -0,0 +1,122 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// The persistent content-addressed disk cache behind offline hot-update: the http+// backend serves cached (content-addressed, immutable) assets without the network,+// the node adapter backs it with a real filesystem, and both cache wrappers degrade+// to "no cache" on a platform (web) that omits the methods.+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { rm } from 'node:fs/promises';+import { HttpBackend } from '../src/asset/Backend';+import { setPlatform, platformReadCacheFile, platformWriteCacheFile } from '../src/platform/base';+import type { PlatformAdapter, PlatformResponse } from '../src/platform/types';+import { nodeAdapter } from '../src/platform/node';++function mockPlatform(over: Partial<PlatformAdapter>): PlatformAdapter {+ return {+ name: 'web',+ fetch: vi.fn(),+ readFile: vi.fn(), readTextFile: vi.fn(), fileExists: vi.fn(),+ loadImagePixels: vi.fn(), instantiateWasm: vi.fn(),+ createCanvas: vi.fn(), createImage: vi.fn(), now: () => 0,+ bindInputEvents: vi.fn(), createAudioBackend: vi.fn(),+ devicePixelRatio: () => 1,+ getStorageItem: () => null, setStorageItem: vi.fn(),+ removeStorageItem: vi.fn(), clearStorage: vi.fn(),+ ...over,+ } as unknown as PlatformAdapter;+}++function okResponse(bytes: ArrayBuffer): PlatformResponse {+ return {+ ok: true, status: 200, statusText: 'OK', headers: {},+ json: async () => ({}), text: async () => '', arrayBuffer: async () => bytes,+ };+}++describe('HttpBackend content cache (offline hot-update store)', () => {+ it('serves a cached http asset without touching the network (offline)', async () => {+ const cached = new Uint8Array([1, 2, 3, 4]).buffer;+ const fetch = vi.fn(() => { throw new Error('offline'); });+ setPlatform(mockPlatform({ fetch: fetch as never, readCacheFile: async () => cached }));++ const got = await new HttpBackend({ baseUrl: '' }).fetchBinary('https://cdn/assets/abcd.png');++ expect(new Uint8Array(got)).toEqual(new Uint8Array([1, 2, 3, 4]));+ expect(fetch).not.toHaveBeenCalled(); // cache hit ⇒ no network+ });++ it('falls through to the network on a cache miss', async () => {+ const net = new Uint8Array([9, 9]).buffer;+ const fetch = vi.fn(async () => okResponse(net));+ setPlatform(mockPlatform({ fetch: fetch as never, readCacheFile: async () => null }));++ const got = await new HttpBackend({ baseUrl: '' }).fetchBinary('https://cdn/assets/x.png');++ expect(new Uint8Array(got)).toEqual(new Uint8Array([9, 9]));+ expect(fetch).toHaveBeenCalledOnce();+ });++ it('never consults the cache for non-http (local/same-origin) paths', async () => {+ const net = new Uint8Array([7]).buffer;+ const readCacheFile = vi.fn(async () => new Uint8Array([0]).buffer);+ const fetch = vi.fn(async () => okResponse(net));+ setPlatform(mockPlatform({ fetch: fetch as never, readCacheFile }));++ const got = await new HttpBackend({ baseUrl: '' }).fetchBinary('estella://project/a.png');++ expect(new Uint8Array(got)).toEqual(new Uint8Array([7]));+ expect(readCacheFile).not.toHaveBeenCalled(); // local path bypasses the cache+ });+});++describe('node adapter disk cache (real filesystem)', () => {+ const dir = join(tmpdir(), `esengine-cache-test-${process.pid}`);+ beforeEach(() => { process.env.ESENGINE_CACHE_DIR = dir; });+ afterEach(async () => {+ delete process.env.ESENGINE_CACHE_DIR;+ await rm(dir, { recursive: true, force: true });+ });++ it('round-trips bytes through the filesystem, misses on an absent key', async () => {+ const key = 'https://cdn/assets/deadbeef.png';+ expect(await nodeAdapter.readCacheFile(key)).toBeNull(); // empty cache++ await nodeAdapter.writeCacheFile(key, new Uint8Array([5, 6, 7, 8, 9]).buffer);+ const got = await nodeAdapter.readCacheFile(key);++ expect(got).not.toBeNull();+ expect(new Uint8Array(got!)).toEqual(new Uint8Array([5, 6, 7, 8, 9]));+ expect(await nodeAdapter.readCacheFile('https://cdn/assets/other.png')).toBeNull();+ });++ it('end-to-end: HttpBackend serves an updated asset from the real disk cache OFFLINE', async () => {+ const url = 'https://cdn/v2/assets/cafebabe.png';+ const bytes = new Uint8Array([10, 20, 30, 40]).buffer;+ // Platform: real node fs cache (temp dir above) + a fetch that always fails (offline).+ const offlineFetch = vi.fn(() => { throw new Error('offline'); });+ setPlatform(mockPlatform({+ fetch: offlineFetch as never,+ readCacheFile: (k) => nodeAdapter.readCacheFile(k),+ writeCacheFile: (k, b) => nodeAdapter.writeCacheFile(k, b),+ }));++ // "applyUpdate" persisted the verified bytes to disk while online…+ await platformWriteCacheFile(url, bytes);+ // …now, offline, the http backend loads them straight off disk (no network).+ const got = await new HttpBackend({ baseUrl: '' }).fetchBinary(url);++ expect(new Uint8Array(got)).toEqual(new Uint8Array([10, 20, 30, 40]));+ expect(offlineFetch).not.toHaveBeenCalled();+ });+});++describe('cache wrappers degrade on a platform with no cache (web)', () => {+ it('read returns null and write no-ops when the adapter omits the methods', async () => {+ setPlatform(mockPlatform({})); // no readCacheFile / writeCacheFile+ expect(await platformReadCacheFile('k')).toBeNull();+ await expect(platformWriteCacheFile('k', new ArrayBuffer(2))).resolves.toBeUndefined();+ });+});diff --git a/sdk/tests/hot-update-runtime.test.ts b/sdk/tests/hot-update-runtime.test.tsindex d51e96aa6..152f5deee 100644--- a/sdk/tests/hot-update-runtime.test.ts+++ b/sdk/tests/hot-update-runtime.test.ts@@ -29,14 +29,18 @@ vi.mock('../src/resourceManager', () => ({evictTextureDimensions: vi.fn(),}));-// In-memory platform storage so persistence round-trips in the test.+// In-memory platform storage + content cache so persistence and the offline+// disk-cache write round-trip in the test.vi.mock('../src/platform', () => {const store = new Map<string, string>();+ const cache = new Map<string, ArrayBuffer>();return {platformLoadSubpackage: vi.fn(() => Promise.resolve()),platformGetStorageItem: (k: string) => store.get(k) ?? null,platformSetStorageItem: (k: string, v: string) => { store.set(k, v); },+ platformWriteCacheFile: vi.fn((k: string, b: ArrayBuffer) => { cache.set(k, b); return Promise.resolve(); }),__store: store,+ __cache: cache,};});@@ -135,6 +139,11 @@ describe('Assets.checkForUpdate / applyUpdate', () => {expect(assets.remoteRoot).toBe('https://cdn/v2');// The changed asset was downloaded + verified from the NEW cdn root.expect(backend.fetchBinary).toHaveBeenCalledWith(`https://cdn/v2/assets/${REMOTE_HASH}.png`);+ // …and its verified bytes were written to the offline disk cache, keyed by+ // the immutable cdn url — so a later boot loads them without the CDN.+ const platform = await import('../src/platform');+ expect((platform as unknown as { __cache: Map<string, ArrayBuffer> })+ .__cache.get(`https://cdn/v2/assets/${REMOTE_HASH}.png`)?.byteLength).toBe(8);// A renderer bound to the changed asset's stable key is told to rebind.expect(rebinds).toEqual(['uuid-1']);expect(progress[0]).toEqual([0, 1]);diff --git a/sdk/tests/native-adapter.test.ts b/sdk/tests/native-adapter.test.tsindex 5b0f610f5..8406d7a02 100644--- a/sdk/tests/native-adapter.test.ts+++ b/sdk/tests/native-adapter.test.ts@@ -19,6 +19,7 @@ import type { InputEventCallbacks } from '../src/platform/types';function makeBridge() {const store = new Map<string, string>();+ const cacheStore = new Map<string, ArrayBuffer>();const files = new Map<string, ArrayBuffer>([['data/config.json', new TextEncoder().encode('{"a":1}').buffer as ArrayBuffer],]);@@ -36,6 +37,8 @@ function makeBridge() {setStorageItem: (k, v) => { store.set(k, v); },removeStorageItem: (k) => { store.delete(k); },storageKeys: () => [...store.keys()],+ readCacheFile: async (k) => cacheStore.get(k) ?? null,+ writeCacheFile: async (k, b) => { cacheStore.set(k, b); },registerInput: (l) => {listeners.push(l);return () => {@@ -47,7 +50,7 @@ function makeBridge() {now: () => 12345,language: () => 'zh_CN',};- return { bridge, store, files, listeners };+ return { bridge, store, cacheStore, files, listeners };}function makeInputCallbacks(): InputEventCallbacks {@@ -159,6 +162,22 @@ describe('NativePlatformAdapter (mock bridge)', () => {expect(() => adapter.createCanvas(1, 1)).toThrow(/native/);expect(() => adapter.createImage()).toThrow(/native/);});++ it('round-trips the offline content cache through the bridge', async () => {+ expect(await adapter.readCacheFile('https://cdn/a.png')).toBeNull();+ await adapter.writeCacheFile('https://cdn/a.png', new Uint8Array([1, 2, 3]).buffer);+ const got = await adapter.readCacheFile('https://cdn/a.png');+ expect(new Uint8Array(got!)).toEqual(new Uint8Array([1, 2, 3]));+ });++ it('degrades to no-cache when the bridge omits cache methods', async () => {+ const bare = makeBridge().bridge as Partial<NativeBridge>;+ delete bare.readCacheFile;+ delete bare.writeCacheFile;+ const a = new NativePlatformAdapter(bare as NativeBridge);+ expect(await a.readCacheFile('x')).toBeNull();+ await expect(a.writeCacheFile('x', new ArrayBuffer(1))).resolves.toBeUndefined();+ });});describe('detectPlatform()', () => {