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.

feat(assets): atomic hot-update apply with download integrity + rollback

yhh944e4af02703
diff --git a/desktop/src/gameHost.ts b/desktop/src/gameHost.ts
index f937d88f6..9237243a5 100644
--- a/desktop/src/gameHost.ts
+++ b/desktop/src/gameHost.ts
@@ -138,11 +138,11 @@ async function boot(): Promise<void> {
/** Drive a hot update against a served (CDN) manifest: fetch + diff + apply.
* Rebinding the visuals is the game's job (via Assets.onInvalidate); a
* driver settles frames after this before re-capturing. */
- async applyRemoteUpdate(manifestUrl: string, remoteRoot?: string): Promise<{ changed: number }> {
+ async applyRemoteUpdate(manifestUrl: string, remoteRoot?: string): Promise<{ changed: number; applied: boolean; failed: number }> {
const assets = app.getResource(Assets);
const plan = await assets.checkForUpdate({ manifestUrl, remoteRoot });
- await assets.applyUpdate();
- return { changed: plan.changedAssets.length };
+ const result = await assets.applyUpdate();
+ return { changed: plan.changedAssets.length, applied: result.ok, failed: result.failed.length };
},
};
}
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 4301759d7..a3c7163ca 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -4,6 +4,7 @@ import type { Backend } from './Backend';
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 type {
AssetLoader, LoadContext, TextureResult, SpineResult,
@@ -53,6 +54,22 @@ export interface CheckForUpdateOptions {
remoteRoot?: string;
}
+/** One asset {@link Assets.applyUpdate} could not deliver: `fetch` (download
+ * failed) or `integrity` (bytes' content hash ≠ the manifest's). */
+export interface AssetDownloadFailure {
+ path: string;
+ reason: 'fetch' | 'integrity';
+}
+
+/** Outcome of {@link Assets.applyUpdate} — atomic: `ok` only when every changed
+ * asset downloaded + verified and the manifest was swapped. On failure nothing
+ * is applied (`updated: 0`) and `failed` lists why (rollback). */
+export interface ApplyUpdateResult {
+ ok: boolean;
+ updated: number;
+ failed: AssetDownloadFailure[];
+}
+
/** The manifest + root staged by checkForUpdate, awaiting applyUpdate. */
interface PendingUpdate {
plan: UpdatePlan;
@@ -578,13 +595,13 @@ export class Assets {
this.remoteRoot_ = url ? url.replace(/\/+$/, '') : undefined;
}
- /** Absolute url of a `remote`-group asset. An already-absolute manifest path
- * (a fully-qualified CDN url) passes through; otherwise it joins the remote
- * root. With no root set the path returns as-is (same-origin fallback). */
- private remoteUrlFor_(path: string): string {
+ /** Absolute url of a `remote`-group asset against `root` (default the active
+ * remote root). An already-absolute manifest path (a fully-qualified CDN url)
+ * passes through; with no root the path returns as-is (same-origin fallback). */
+ private remoteUrlFor_(path: string, root: string | undefined = this.remoteRoot_): string {
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path)) return path;
- if (!this.remoteRoot_) return path;
- return `${this.remoteRoot_}/${path.replace(/^\/+/, '')}`;
+ if (!root) return path;
+ return `${root.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`;
}
/**
@@ -608,56 +625,74 @@ export class Assets {
}
/**
- * Apply the update staged by the last {@link checkForUpdate}: point remote
- * resolution at its root, make its manifest active, download the changed
- * (content-addressed) assets from the CDN with progress, notify live handles
- * bound to a changed asset to rebind (via the `onInvalidate` channel), and
- * persist the manifest so a returning player boots on it. No-op with nothing
- * staged.
+ * Apply the update staged by the last {@link checkForUpdate}, ATOMICALLY.
+ * Phase 1 downloads AND integrity-verifies every changed (content-addressed)
+ * asset — bytes are hashed and checked against the manifest's `contentHash`,
+ * so a corrupted / tampered CDN response is caught. Only if ALL succeed does
+ * phase 2 commit: swap the active manifest + root, rebind live handles (via
+ * `onInvalidate`), and persist. If any asset fails to download or fails its
+ * hash check, NOTHING is swapped — the old manifest stays active (rollback)
+ * and the failures are returned. No-op with nothing staged.
*/
- async applyUpdate(onProgress?: (loaded: number, total: number) => void): Promise<void> {
+ async applyUpdate(onProgress?: (loaded: number, total: number) => void): Promise<ApplyUpdateResult> {
const pending = this.pendingUpdate_;
if (!pending) {
log.warn('asset', 'applyUpdate() called with no pending update — call checkForUpdate first');
onProgress?.(0, 0);
- return;
+ return { ok: false, updated: 0, failed: [] };
}
- // Swap FIRST so changed assets resolve to their new remote urls, then warm
- // them. Content addressing makes the download purely additive to the cache.
- if (pending.remoteRoot != null) this.setRemoteRoot(pending.remoteRoot);
- this.setManifest(pending.model);
-
const changed = pending.plan.changedAssets;
+ const root = pending.remoteRoot ?? undefined;
+
+ // Phase 1 — download + verify EVERY changed asset WITHOUT touching the
+ // active manifest. Content-addressed, so these are brand-new urls (nothing
+ // is overwritten); any failure here leaves the old manifest active = rollback.
+ const failed: AssetDownloadFailure[] = [];
let done = 0;
onProgress?.(0, changed.length);
const tasks = changed.map((c) => async (): Promise<void> => {
- try {
- await this.downloadChangedAsset_(c);
- } catch (e) {
- log.warn('asset', `applyUpdate: failed to fetch ${c.path}`, e);
- }
+ const reason = await this.fetchAndVerify_(c, pending.model, root);
+ if (reason) failed.push({ path: c.path, reason });
});
await runWithConcurrency(tasks, DEFAULT_PRELOAD_CONCURRENCY, () => {
onProgress?.(++done, changed.length);
});
- // Rebind: tell renderers holding a stale handle for a changed asset to
- // re-resolve it against the now-active manifest → the freshly-warmed
- // content. Old, differently-keyed handles orphan and release by refcount.
- for (const c of changed) this.fireInvalidate_(c.key);
+ if (failed.length > 0) {
+ log.warn('asset', `applyUpdate: ${failed.length}/${changed.length} asset(s) failed — update rolled back (manifest unchanged)`);
+ return { ok: false, updated: 0, failed };
+ }
+ // Phase 2 — commit atomically: swap root + manifest, rebind, persist. Renderers
+ // holding a stale handle for a changed asset re-resolve against the now-active
+ // manifest (the freshly-fetched content); old handles orphan + release by refcount.
+ if (pending.remoteRoot != null) this.setRemoteRoot(pending.remoteRoot);
+ this.setManifest(pending.model);
+ for (const c of changed) this.fireInvalidate_(c.key);
this.persistActiveManifest_(pending.manifestJson);
this.pendingUpdate_ = null;
+ return { ok: true, updated: changed.length, failed: [] };
}
- /** Warm one changed asset from its group's delivery source (remote → CDN url,
- * else the normal resolved path) through its typed loader. */
- private downloadChangedAsset_(c: AssetChange): Promise<unknown> {
- const group = this.manifestModel_?.group(c.group);
+ /** Download one changed asset's bytes from its delivery source (remote → CDN
+ * url against `root`, else the normal resolved path) and verify the content
+ * hash. Null on success, else the failure reason. Uses the PENDING manifest +
+ * root — phase 1 runs before the swap. */
+ private async fetchAndVerify_(
+ c: AssetChange, model: ManifestModel, root: string | undefined,
+ ): Promise<AssetDownloadFailure['reason'] | null> {
+ const group = model.group(c.group);
const remote = group != null && normalizeBundleMode(group.bundleMode) === 'remote';
- const path = remote ? this.remoteUrlFor_(c.path) : this.resolveLoadPath_(c.path);
- const load = this.typedLoadFor_(path, c.type);
- return load ? load() : Promise.resolve();
+ const path = remote ? this.remoteUrlFor_(c.path, root) : this.resolveLoadPath_(c.path);
+ try {
+ const buf = await this.backend.fetchBinary(this.backend.resolveUrl(path));
+ if (c.contentHash && contentHashHex(new Uint8Array(buf)) !== c.contentHash) {
+ return 'integrity';
+ }
+ return null;
+ } catch {
+ return 'fetch';
+ }
}
/**
diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.ts
index 4936246a1..8eddee549 100644
--- a/sdk/src/asset/index.ts
+++ b/sdk/src/asset/index.ts
@@ -31,7 +31,7 @@ export { Assets, AssetPlugin, assetPlugin, type AssetsData } from './AssetPlugin
export { decodeImageBitmap, decodeImagePixels, imageBitmapOptions, type DecodedPixels } from './imageDecode';
export { AssetRefCounter, type AssetRefInfo } from './AssetRefCounter';
-export { Assets as AssetsImpl, type AssetsOptions, type AssetBundle, type SceneAssetResult, type MissingAsset, type CheckForUpdateOptions, type InvalidateListener } from './Assets';
+export { Assets as AssetsImpl, type AssetsOptions, type AssetBundle, type SceneAssetResult, type MissingAsset, type CheckForUpdateOptions, type ApplyUpdateResult, type AssetDownloadFailure, type InvalidateListener } from './Assets';
export { type Backend, HttpBackend, EmbeddedBackend, type HttpBackendOptions } from './Backend';
export { Catalog, atlasCatalogFields, type CatalogData, type CatalogEntry, type AtlasFrameInfo, type CookedAtlasInfo } from './Catalog';
export {
diff --git a/sdk/tests/hot-update-runtime.test.ts b/sdk/tests/hot-update-runtime.test.ts
index 7c2fca721..194b8a541 100644
--- a/sdk/tests/hot-update-runtime.test.ts
+++ b/sdk/tests/hot-update-runtime.test.ts
@@ -5,6 +5,11 @@ import { Assets } from '../src/asset/Assets';
import { Catalog } from '../src/asset/Catalog';
import type { AddressableManifest } from '../src/asset/AddressableManifest';
import type { Backend } from '../src/asset/Backend';
+import { contentHashHex } from '../src/asset/contentHash';
+
+// The bytes backendServing.fetchBinary returns (8 zero bytes) → the content hash a
+// candidate manifest must claim for the integrity check to pass.
+const REMOTE_HASH = contentHashHex(new Uint8Array(8));
const mockModule = {
_malloc: vi.fn(() => 0),
@@ -112,30 +117,63 @@ describe('Assets.checkForUpdate / applyUpdate', () => {
expect(assets.remoteRoot).toBe('https://cdn/v1');
});
- it('applyUpdate swaps the manifest+root, downloads changed assets, and notifies listeners', async () => {
- const assets = createAssets(backendServing(cdnManifest('zzzz', 'rev-2')));
+ it('applyUpdate downloads+verifies, then atomically swaps manifest+root and notifies', async () => {
+ const backend = backendServing(cdnManifest(REMOTE_HASH, 'rev-2'));
+ const assets = createAssets(backend);
assets.setManifest(cdnManifest('aaaa', 'rev-1'));
assets.setRemoteRoot('https://cdn/v1');
- const spy = vi.spyOn(assets, 'loadTexture')
- .mockResolvedValue({ handle: 2, width: 1, height: 1 } as any);
const rebinds: string[] = [];
assets.onInvalidate((ref) => rebinds.push(ref));
await assets.checkForUpdate({ manifestUrl: 'asset-manifest.json', remoteRoot: 'https://cdn/v2' });
const progress: [number, number][] = [];
- await assets.applyUpdate((loaded, total) => progress.push([loaded, total]));
+ const result = await assets.applyUpdate((loaded, total) => progress.push([loaded, total]));
+ expect(result).toEqual({ ok: true, updated: 1, failed: [] });
// Manifest + root are now the update's.
expect(assets.getManifest()?.revision()).toBe('rev-2');
expect(assets.remoteRoot).toBe('https://cdn/v2');
- // The changed asset was fetched from the NEW cdn root.
- expect(spy).toHaveBeenCalledWith('https://cdn/v2/assets/zzzz.png');
+ // The changed asset was downloaded + verified from the NEW cdn root.
+ expect(backend.fetchBinary).toHaveBeenCalledWith(`https://cdn/v2/assets/${REMOTE_HASH}.png`);
// 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]);
expect(progress[progress.length - 1]).toEqual([1, 1]);
});
+ it('applyUpdate rolls back (manifest unchanged, no rebind) on an integrity mismatch', async () => {
+ // The candidate manifest claims a hash the served bytes do not match.
+ const assets = createAssets(backendServing(cdnManifest('deadbeefdeadbeef', 'rev-2')));
+ assets.setManifest(cdnManifest('aaaa', 'rev-1'));
+ assets.setRemoteRoot('https://cdn/v1');
+ const rebinds: string[] = [];
+ assets.onInvalidate((ref) => rebinds.push(ref));
+
+ await assets.checkForUpdate({ manifestUrl: 'asset-manifest.json', remoteRoot: 'https://cdn/v2' });
+ const result = await assets.applyUpdate();
+
+ expect(result.ok).toBe(false);
+ expect(result.failed).toEqual([{ path: 'assets/deadbeefdeadbeef.png', reason: 'integrity' }]);
+ // Rolled back: the old manifest + root stay active and nobody rebound.
+ expect(assets.getManifest()?.revision()).toBe('rev-1');
+ expect(assets.remoteRoot).toBe('https://cdn/v1');
+ expect(rebinds).toEqual([]);
+ });
+
+ it('applyUpdate rolls back when a download fails', async () => {
+ const backend = backendServing(cdnManifest(REMOTE_HASH, 'rev-2'));
+ (backend.fetchBinary as any).mockRejectedValue(new Error('network'));
+ const assets = createAssets(backend);
+ assets.setManifest(cdnManifest('aaaa', 'rev-1'));
+
+ await assets.checkForUpdate({ manifestUrl: 'asset-manifest.json', remoteRoot: 'https://cdn/v2' });
+ const result = await assets.applyUpdate();
+
+ expect(result.ok).toBe(false);
+ expect(result.failed[0].reason).toBe('fetch');
+ expect(assets.getManifest()?.revision()).toBe('rev-1'); // unchanged
+ });
+
it('applyUpdate is a no-op without a prior checkForUpdate', async () => {
const assets = createAssets(backendServing());
assets.setManifest(cdnManifest('aaaa', 'rev-1'));
@@ -148,11 +186,10 @@ describe('Assets.checkForUpdate / applyUpdate', () => {
describe('Assets.restorePersistedUpdate', () => {
it('persists an applied update and restores it into a fresh Assets', async () => {
- const backend = backendServing(cdnManifest('zzzz', 'rev-2'));
+ const backend = backendServing(cdnManifest(REMOTE_HASH, 'rev-2'));
const first = createAssets(backend);
first.setManifest(cdnManifest('aaaa', 'rev-1'));
first.setRemoteRoot('https://cdn/v1');
- vi.spyOn(first, 'loadTexture').mockResolvedValue({ handle: 1, width: 1, height: 1 } as any);
// Arm persistence (nothing stored yet → false), then update.
expect(first.restorePersistedUpdate('hotupdate:demo')).toBe(false);