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(platform): a hot update on a native build is stored under a name the host accepts
esengine5297880daac1
diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsindex ffd664a87..ec805b927 100644--- a/sdk/src/platform/base.ts+++ b/sdk/src/platform/base.ts@@ -8,6 +8,9 @@import type { PlatformAdapter } from './types';import type { PlatformAudioBackend } from '../audio/PlatformAudioBackend';import { NullAudioBackend } from '../audio/NullAudioBackend';+import { log } from '../util/logger';++let cacheWriteFailureReported = false;// =============================================================================// Platform Instance (set by entry point)@@ -212,16 +215,19 @@ export async function platformReadCacheFile(key: string): Promise<ArrayBuffer |}/** 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). */+ * cache (web) or is uninitialized (tests). A failed write never fails the update,+ * but it is said once: silence is how the native host refused every write unseen. */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+ } catch (err) {+ if (!cacheWriteFailureReported) {+ cacheWriteFailureReported = true;+ log.warn('asset', `cache write failed, so updated assets will need the network next launch: ${String(err)}`);+ }}}diff --git a/sdk/src/platform/cacheEntryName.ts b/sdk/src/platform/cacheEntryName.tsnew file mode 100644index 000000000..23d53fbfe--- /dev/null+++ b/sdk/src/platform/cacheEntryName.ts@@ -0,0 +1,16 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file cacheEntryName.ts — the file a content cache key is stored under.+ */+import { contentHashHex } from '../asset/contentHash';+import { encodeUtf8 } from '../util/utf8';++/**+ * The key's XXH64, as 16 hex digits. A key is a content-addressed url, which no+ * filesystem name holds as-is, and the native host refuses any name outside+ * `[A-Za-z0-9._-]` — so every platform with a disk cache stores under this.+ */+export function cacheEntryName(key: string): string {+ return contentHashHex(encodeUtf8(key));+}diff --git a/sdk/src/platform/native/hostBridge.ts b/sdk/src/platform/native/hostBridge.tsindex 4314a9fc6..bfc1d9973 100644--- a/sdk/src/platform/native/hostBridge.ts+++ b/sdk/src/platform/native/hostBridge.ts@@ -19,6 +19,7 @@ import type {} from './bridge';import type { PlatformGlyph, PlatformGlyphRequest, PlatformRequestOptions } from '../types';import { assertHostEnvironment } from './hostEnvironment';+import { cacheEntryName } from '../cacheEntryName';import { hasAudioBindings } from '../../ecs/bridge/nativeBindings';/** Touch phases the host reports, matching the order it dispatches. */@@ -202,11 +203,10 @@ export function createHostBridge(...storage,...(bindings.es_readCacheFile && bindings.es_writeCacheFile? {- readCacheFile: (key: string) => Promise.resolve(bindings.es_readCacheFile!(key)),- writeCacheFile: (key: string, bytes: ArrayBuffer) => {- bindings.es_writeCacheFile!(key, bytes);- return Promise.resolve();- },+ readCacheFile: (key: string) => Promise.resolve(bindings.es_readCacheFile!(cacheEntryName(key))),+ writeCacheFile: (key: string, bytes: ArrayBuffer) => bindings.es_writeCacheFile!(cacheEntryName(key), bytes)+ ? Promise.resolve()+ : Promise.reject(new Error(`the host refused to cache ${key}`)),}: {}),registerInput: (sink) => {diff --git a/sdk/src/platform/node.ts b/sdk/src/platform/node.tsindex 1ba9bd4e9..5b6450ccb 100644--- a/sdk/src/platform/node.ts+++ b/sdk/src/platform/node.ts@@ -14,7 +14,6 @@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,@@ -28,6 +27,7 @@ import type {PlatformSocketOptions,} from './types';import { GameSocket } from '../net/GameSocket';+import { cacheEntryName } from './cacheEntryName';function isUrl(path: string): boolean {return /^https?:\/\//.test(path);@@ -161,15 +161,13 @@ class NodePlatformAdapter implements PlatformAdapter {}// 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).+ // OS temp dir; override with ESENGINE_CACHE_DIR.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'));+ return join(this.cacheDir_(), cacheEntryName(key));}async readCacheFile(key: string): Promise<ArrayBuffer | null> {diff --git a/sdk/tests/native-host-bridge.test.ts b/sdk/tests/native-host-bridge.test.tsindex f1e900f1d..4aea13578 100644--- a/sdk/tests/native-host-bridge.test.ts+++ b/sdk/tests/native-host-bridge.test.ts@@ -74,6 +74,45 @@ describe('createHostBridge', () => {expect(sink.onTouchStart).toHaveBeenCalledTimes(1);});+ /** The host's cache as AssetBindings.cpp keeps it: a name outside+ * [A-Za-z0-9._-] is refused, a write answers false and a read answers null. */+ const strictCacheScope = () => {+ const files = new Map<string, ArrayBuffer>();+ const accepted = (name: string) => /^[A-Za-z0-9._-]+$/.test(name);+ return {+ files,+ scope: hostScope({+ es_readCacheFile: (name: string) => (accepted(name) ? files.get(name) ?? null : null),+ es_writeCacheFile: (name: string, bytes: ArrayBuffer) => {+ if (!accepted(name)) return false;+ files.set(name, bytes);+ return true;+ },+ }),+ };+ };++ it('caches a hot update under a name the host accepts, and reads it back', async () => {+ const { scope, files } = strictCacheScope();+ const bridge = createHostBridge(scope);+ const url = 'https://cdn.example.com/v2/assets/9f86d081884c7d65.png';++ await bridge.writeCacheFile!(url, new Uint8Array([1, 2, 3]).buffer);++ expect(files.size).toBe(1);+ const read = await bridge.readCacheFile!(url);+ expect(read && [...new Uint8Array(read)]).toEqual([1, 2, 3]);+ expect(await bridge.readCacheFile!('https://cdn.example.com/v2/assets/other.png')).toBeNull();+ });++ it('reports a write the host refused instead of pretending it landed', async () => {+ const bridge = createHostBridge(hostScope({+ es_readCacheFile: () => null,+ es_writeCacheFile: () => false,+ }));+ await expect(bridge.writeCacheFile!('https://cdn.example.com/a.png', new ArrayBuffer(1))).rejects.toThrow(/refused/);+ });+/** A host with both stores, kept apart so a test can say which one was written. */const twoStoreScope = (): { scope: ReturnType<typeof hostScope>; cache: Map<string, string>; data: Map<string, string> } => {const cache = new Map<string, string>();