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(hot-update): an update says which stages it reached, and the next launch starts on a whole version

esengine16be40067d24
diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.ts
index 893069b30..459c37588 100644
--- a/pipeline/src/runtime/gameHost.ts
+++ b/pipeline/src/runtime/gameHost.ts
@@ -854,12 +854,16 @@ 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; applied: boolean; failed: number }> {
+ async applyRemoteUpdate(manifestUrl: string, remoteRoot?: string) {
const assets = app.getResource(Assets);
const plan = await assets.checkForUpdate({ manifestUrl, remoteRoot });
const result = await assets.applyUpdate();
- return { changed: plan.changedAssets.length, applied: result.ok, failed: result.failed.length };
+ return {
+ changed: plan.changedAssets.length, applied: result.ok, failed: result.failed.length,
+ stages: result.stages, revision: result.revision,
+ };
},
+ updateStatus: () => app.getResource(Assets).updateStatus(),
};
// Each behind its OWN export. They are different ABIs now: readying a
// prepared cell ships, and deriving the same from live entities is the
diff --git a/pipeline/tests/hotupdate-verify-fixture.test.ts b/pipeline/tests/hotupdate-verify-fixture.test.ts
index ce6924589..4e9da2b1c 100644
--- a/pipeline/tests/hotupdate-verify-fixture.test.ts
+++ b/pipeline/tests/hotupdate-verify-fixture.test.ts
@@ -34,6 +34,8 @@ const opts = (root: string, outDir: string) => ({
outDir,
title: 'Hot Update Demo',
contentAddressed: true,
+ // A game that updates stores what it applied; the verifier relaunches to see it.
+ hotUpdate: { persistUpdateKey: 'esengine:hotupdate:verify' },
});
describe.skipIf(!process.env.ESTELLA_HOTUPDATE_FIXTURE)('hot-update verify fixture', () => {
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 502126c16..4cf04d781 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, type AddressableAssetType } from './AddressableManifest';
import { diffManifests, type UpdatePlan, type AssetChange } from './hotUpdate';
import { contentHashHex } from './contentHash';
-import { platformLoadSubpackage, platformGetStorageItem, platformSetStorageItem, platformWriteCacheFile } from '../platform';
+import { platformLoadSubpackage, platformGetStorageItem, platformSetStorageItem, platformRemoveStorageItem, platformWriteCacheFile } from '../platform';
import type {
AssetLoader, LoadContext, TextureResult, SpineResult,
MaterialResult, FontResult, AudioResult, AnimClipResult,
@@ -93,6 +93,22 @@ export interface AssetDownloadFailure {
reason: 'fetch' | 'integrity';
}
+/**
+ * How far an update got. Each is its own answer: an update can be running in this
+ * session and still be gone on the next launch, which a single `ok` cannot say.
+ */
+export interface UpdateStages {
+ /** Every changed asset downloaded and matched its content hash. */
+ verified: boolean;
+ /** This session runs on the new manifest, and its asset graph has settled on it. */
+ applied: boolean;
+ /** The next launch starts on it: stored, and read back. Null without a persistence key. */
+ persisted: boolean | null;
+ /** Every changed remote asset is in the disk cache, so the next launch reads them
+ * without the network. Null where the platform keeps no cache. */
+ cached: boolean | null;
+}
+
/** 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). */
@@ -100,11 +116,28 @@ export interface ApplyUpdateResult {
ok: boolean;
updated: number;
failed: AssetDownloadFailure[];
+ stages: UpdateStages;
+ /** The revision this session runs on afterwards. */
+ revision: string | null;
+ /** The changed assets the cache refused, by url: what the next launch fetches again. */
+ uncached: string[];
+ /** Why nothing was attempted: no update staged (none checked, or another apply took it). */
+ reason?: 'nothing-staged';
+}
+
+/** What {@link Assets.updateStatus} reports. */
+export interface UpdateStatus {
+ /** The revision this session runs on. */
+ revision: string | null;
+ /** The revision the next launch starts on, when an update was persisted. */
+ persistedRevision: string | null;
+ /** The update {@link Assets.checkForUpdate} staged, and what applying it downloads. */
+ staged: { revision: string | null; assets: number; bytes: number } | null;
+ applying: boolean;
}
/** The manifest + root staged by checkForUpdate, awaiting applyUpdate. */
interface PendingUpdate {
- plan: UpdatePlan;
model: ManifestModel;
manifestJson: AddressableManifest;
remoteRoot: string | null;
@@ -350,11 +383,17 @@ export class Assets {
private manifestModel_: ManifestModel | null = null;
/** CDN root that `remote`-group assets resolve against; see {@link setRemoteRoot}. */
private remoteRoot_?: string;
+ /** Applies run one after another: two at once would each commit, and one that
+ * finishes after a newer check would clear the newer candidate. */
+ private applyChain_: Promise<unknown> = Promise.resolve();
+ private applying_ = 0;
/** The update staged by {@link checkForUpdate}, consumed by {@link applyUpdate}. */
private pendingUpdate_: PendingUpdate | null = null;
/** Storage key {@link applyUpdate} persists the active manifest under; set by
* {@link restorePersistedUpdate}. Null → persistence off. */
private persistKey_: string | null = null;
+ /** The revision this package shipped, read when persistence is armed at boot. */
+ private shippedRevision_: string | null = null;
private getAudio_: () => import('../audio/Audio').AudioAPI | null;
private getSpriteAnimation_: () => import('../animation/SpriteAnimator').SpriteAnimationAPI | null;
private getLocalization_: () => import('../i18n/Localization').LocalizationAPI | null;
@@ -1010,7 +1049,7 @@ export class Assets {
const model = ManifestModel.fromJson(json);
const plan = diffManifests(this.manifestModel_, model);
const remoteRoot = options.remoteRoot ?? this.remoteRoot_ ?? null;
- this.pendingUpdate_ = { plan, model, manifestJson: json, remoteRoot };
+ this.pendingUpdate_ = { model, manifestJson: json, remoteRoot };
return plan;
}
@@ -1025,24 +1064,43 @@ export class Assets {
* and the failures are returned. No-op with nothing staged.
*/
async applyUpdate(onProgress?: (loaded: number, total: number) => void): Promise<ApplyUpdateResult> {
+ this.applying_++;
+ const run = this.applyChain_.then(() => this.applyStaged_(onProgress));
+ this.applyChain_ = run.catch(() => {});
+ try {
+ return await run;
+ } finally {
+ this.applying_--;
+ }
+ }
+
+ private async applyStaged_(onProgress?: (loaded: number, total: number) => void): Promise<ApplyUpdateResult> {
const pending = this.pendingUpdate_;
+ const revision = (): string | null => this.manifestModel_?.revision() ?? null;
+ const none: UpdateStages = { verified: false, applied: false, persisted: false, cached: false };
if (!pending) {
log.warn('asset', 'applyUpdate() called with no pending update — call checkForUpdate first');
onProgress?.(0, 0);
- return { ok: false, updated: 0, failed: [] };
+ return { ok: false, updated: 0, failed: [], stages: none, revision: revision(), uncached: [], reason: 'nothing-staged' };
}
- const changed = pending.plan.changedAssets;
+ // Against what runs NOW, not what ran when it was checked: an apply that
+ // finished in between moved the base, and its assets need no second download.
+ const changed = diffManifests(this.manifestModel_, pending.model).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[] = [];
+ const uncached: string[] = [];
+ let cacheable = false;
let done = 0;
onProgress?.(0, changed.length);
const tasks = changed.map((c) => async (): Promise<void> => {
- const reason = await this.fetchAndVerify_(c, pending.model, root);
- if (reason) failed.push({ path: c.path, reason });
+ const got = await this.fetchAndVerify_(c, pending.model, root);
+ if (got.failure) failed.push({ path: c.path, reason: got.failure });
+ if (got.cache !== 'unsupported' && got.cache !== undefined) cacheable = true;
+ if (got.cache === 'failed') uncached.push(got.url);
});
await runWithConcurrency(tasks, DEFAULT_PRELOAD_CONCURRENCY, () => {
onProgress?.(++done, changed.length);
@@ -1050,7 +1108,7 @@ export class Assets {
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 };
+ return { ok: false, updated: 0, failed, stages: none, revision: revision(), uncached: [] };
}
// Phase 2 — commit atomically. Capture the texture handle bound to each
@@ -1067,6 +1125,8 @@ export class Assets {
}
if (pending.remoteRoot != null) this.setRemoteRoot(pending.remoteRoot);
this.setManifest(pending.model);
+ // A newer check staged while this one downloaded stays staged.
+ if (this.pendingUpdate_ === pending) this.pendingUpdate_ = null;
// The manifest record already says what kind each changed asset is; the
// notification carries it rather than collapsing to "maybe a texture".
// Changing content and rebinding nothing had no words: every holder keeps
@@ -1092,9 +1152,31 @@ export class Assets {
// not when the manifest was swapped. Bindings converge on a frame, which
// an app that is not ticking would never reach from here.
await this.assetGraphSettled();
- this.persistActiveManifest_(pending.manifestJson);
- this.pendingUpdate_ = null;
- return { ok: true, updated: changed.length, failed: [] };
+ const persisted = this.persistActiveManifest_(pending.manifestJson);
+ if (persisted !== true) {
+ log.warn('asset', persisted === false
+ ? 'applyUpdate: the update runs now, but was not stored — the next launch starts on the previous version'
+ : 'applyUpdate: no persistence key (restorePersistedUpdate was never called), so the next launch starts on what shipped');
+ }
+ return {
+ ok: true, updated: changed.length, failed: [], revision: revision(), uncached,
+ stages: { verified: true, applied: true, persisted, cached: cacheable ? uncached.length === 0 : null },
+ };
+ }
+
+ /** Which revision runs, which one the next launch starts on, and what is staged. */
+ updateStatus(): UpdateStatus {
+ const pending = this.pendingUpdate_;
+ const changed = pending ? diffManifests(this.manifestModel_, pending.model).changedAssets : [];
+ return {
+ revision: this.manifestModel_?.revision() ?? null,
+ persistedRevision: this.persistedRevision_(),
+ staged: pending ? {
+ revision: pending.model.revision(), assets: changed.length,
+ bytes: changed.reduce((n, c) => n + c.size, 0),
+ } : null,
+ applying: this.applying_ > 0,
+ };
}
/** Download one changed asset's bytes from its delivery source (remote → CDN
@@ -1103,24 +1185,22 @@ export class Assets {
* root — phase 1 runs before the swap. */
private async fetchAndVerify_(
c: AssetChange, model: ManifestModel, root: string | undefined,
- ): Promise<AssetDownloadFailure['reason'] | null> {
+ ): Promise<{ url: string; failure?: AssetDownloadFailure['reason']; cache?: 'stored' | 'failed' | 'unsupported' }> {
const group = model.group(c.group);
const remote = group != null && normalizeBundleMode(group.bundleMode) === 'remote';
const path = this.manifestAssetUrl_(c.path, remote, root);
+ const url = this.backend.resolveUrl(path);
try {
- const url = this.backend.resolveUrl(path);
const buf = await this.backend.fetchBinary(url);
if (c.contentHash && contentHashHex(new Uint8Array(buf)) !== c.contentHash) {
- return 'integrity';
+ return { url, failure: '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;
+ // Verified, content-addressed bytes go to the disk cache keyed by the
+ // immutable CDN url, so the next launch reads them offline. A refused
+ // write does not fail the update; it is reported as not cached.
+ return { url, cache: remote ? await platformWriteCacheFile(url, buf) : undefined };
} catch {
- return 'fetch';
+ return { url, failure: 'fetch' };
}
}
@@ -1133,10 +1213,19 @@ export class Assets {
*/
restorePersistedUpdate(key: string): boolean {
this.persistKey_ = key;
+ // What this package shipped: an update stored against any other package is
+ // older than what the player now has installed.
+ this.shippedRevision_ = this.manifestModel_?.revision() ?? null;
const raw = platformGetStorageItem(key);
if (!raw) return false;
try {
- const parsed = JSON.parse(raw) as { manifest: AddressableManifest; remoteRoot?: string | null };
+ const parsed = JSON.parse(raw) as { manifest: AddressableManifest; remoteRoot?: string | null; base?: string | null };
+ if (parsed.base === undefined || parsed.base !== this.shippedRevision_) {
+ log.info('asset', `a stored update (${parsed.manifest?.revision ?? '?'}) was made for another package `
+ + `(${parsed.base ?? 'unknown'}, this one ships ${this.shippedRevision_ ?? 'none'}) — starting on what shipped`);
+ platformRemoveStorageItem(key);
+ return false;
+ }
if (parsed.remoteRoot) this.setRemoteRoot(parsed.remoteRoot);
this.setManifest(parsed.manifest);
return true;
@@ -1146,15 +1235,27 @@ export class Assets {
}
}
- private persistActiveManifest_(json: AddressableManifest): void {
- if (!this.persistKey_) return;
+ /** True once stored and read back; a store can drop a write without throwing.
+ * Null with no persistence key. */
+ private persistActiveManifest_(json: AddressableManifest): boolean | null {
+ if (!this.persistKey_) return null;
+ const value = JSON.stringify({ manifest: json, remoteRoot: this.remoteRoot_ ?? null, base: this.shippedRevision_ });
try {
- platformSetStorageItem(
- this.persistKey_,
- JSON.stringify({ manifest: json, remoteRoot: this.remoteRoot_ ?? null }),
- );
+ platformSetStorageItem(this.persistKey_, value);
+ return platformGetStorageItem(this.persistKey_) === value;
} catch (e) {
log.warn('asset', 'failed to persist updated manifest', e);
+ return false;
+ }
+ }
+
+ private persistedRevision_(): string | null {
+ const raw = this.persistKey_ ? platformGetStorageItem(this.persistKey_) : null;
+ if (!raw) return null;
+ try {
+ return (JSON.parse(raw) as { manifest?: AddressableManifest }).manifest?.revision ?? null;
+ } catch {
+ return null;
}
}
diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.ts
index 5654192f8..470c278f4 100644
--- a/sdk/src/asset/index.ts
+++ b/sdk/src/asset/index.ts
@@ -40,7 +40,7 @@ export { Assets, AssetPlugin, assetPlugin, type AssetsData } from './AssetPlugin
export { decodeImageBitmap, decodeImagePixels, imageBitmapOptions, type DecodedPixels, fetchDecodePixels } from './imageDecode';
export { AssetRefCounter, type AssetRefInfo } from './AssetRefCounter';
-export { Assets as AssetsImpl, type AssetsOptions, type AssetBundle, type SceneAssetResult, type MissingAsset, type CheckForUpdateOptions, type ApplyUpdateResult, type AssetDownloadFailure, type InvalidateListener, type AssetInvalidation } from './Assets';
+export { Assets as AssetsImpl, type AssetsOptions, type AssetBundle, type SceneAssetResult, type MissingAsset, type CheckForUpdateOptions, type ApplyUpdateResult, type UpdateStages, type UpdateStatus, type AssetDownloadFailure, type InvalidateListener, type AssetInvalidation } 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/src/core-content.ts b/sdk/src/core-content.ts
index 5d9b1be0e..8e4d35d04 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -105,6 +105,9 @@ export {
textureFormatOf,
type TextureFormatReport,
type TextureFormatRecord,
+ type ApplyUpdateResult,
+ type UpdateStages,
+ type UpdateStatus,
} from './asset';
/** When the live bindings that READ the asset graph have caught up with it —
diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.ts
index c18929d5f..d30dc3327 100644
--- a/sdk/src/platform/base.ts
+++ b/sdk/src/platform/base.ts
@@ -214,20 +214,22 @@ 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). 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;
+/** Persist a content-addressed asset to the cache: `stored`, `failed` (said once in
+ * the log as well), or `unsupported` where the platform keeps no cache (web) or is
+ * uninitialized (tests). A caller decides what a failed write means for it. */
+export async function platformWriteCacheFile(key: string, bytes: ArrayBuffer): Promise<'stored' | 'failed' | 'unsupported'> {
+ if (!isPlatformInitialized()) return 'unsupported';
const p = getPlatform();
- if (!p.writeCacheFile) return;
+ if (!p.writeCacheFile) return 'unsupported';
try {
await p.writeCacheFile(key, bytes);
+ return 'stored';
} catch (err) {
if (!cacheWriteFailureReported) {
cacheWriteFailureReported = true;
log.warn('asset', `cache write failed, so updated assets will need the network next launch: ${String(err)}`);
}
+ return 'failed';
}
}
@@ -289,6 +291,11 @@ export function platformSetStorageItem(key: string, value: string): void {
getPlatform().setStorageItem(key, value);
}
+export function platformRemoveStorageItem(key: string): void {
+ if (!isPlatformInitialized()) return;
+ getPlatform().removeStorageItem(key);
+}
+
/** Whether this platform can mint ad units at all, without minting one (a
* mini-game host materializes a real host object per created unit). */
export function platformCanCreateAds(): boolean {
diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.ts
index f7a016c4f..ac17a38f5 100644
--- a/sdk/src/platform/index.ts
+++ b/sdk/src/platform/index.ts
@@ -55,6 +55,7 @@ export {
platformOnAppHide,
platformGetStorageItem,
platformSetStorageItem,
+ platformRemoveStorageItem,
platformDevicePixelRatio,
platformLanguage,
platformCanCreateAds,
diff --git a/sdk/tests/content-cache.test.ts b/sdk/tests/content-cache.test.ts
index acdbf8972..4e23da738 100644
--- a/sdk/tests/content-cache.test.ts
+++ b/sdk/tests/content-cache.test.ts
@@ -114,9 +114,9 @@ describe('node adapter disk cache (real filesystem)', () => {
});
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 () => {
+ it('read returns null and write says unsupported 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();
+ await expect(platformWriteCacheFile('k', new ArrayBuffer(2))).resolves.toBe('unsupported');
});
});
diff --git a/sdk/tests/hot-update-reliability.test.ts b/sdk/tests/hot-update-reliability.test.ts
new file mode 100644
index 000000000..37dfbd735
--- /dev/null
+++ b/sdk/tests/hot-update-reliability.test.ts
@@ -0,0 +1,233 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A hot update reports each stage it reached, not one ok, and the next
+ * launch starts on a complete version — faults injected where a device
+ * meets them: a store that refuses, a cache that refuses, a download that
+ * is still running when another update is found or applied.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+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';
+
+const mockModule = { _malloc: vi.fn(() => 0), _free: vi.fn(), HEAPU8: new Uint8Array(1024), GL: null, FS: null } as any;
+
+vi.mock('../src/wasm/resourceManager', () => ({
+ requireResourceManager: () => ({ createTexture: vi.fn(() => 42), releaseTexture: vi.fn(), invalidateTexturePath: vi.fn(() => false) }),
+ getResourceManager: () => null,
+ evictTextureDimensions: vi.fn(),
+}));
+
+const faults = { storeRefuses: false, storeDrops: false, cacheRefuses: false, noCache: false };
+const store = new Map<string, string>();
+const cache = new Map<string, ArrayBuffer>();
+
+vi.mock('../src/platform', () => ({
+ platformLoadSubpackage: vi.fn(() => Promise.resolve()),
+ platformGetStorageItem: (k: string) => store.get(k) ?? null,
+ platformRemoveStorageItem: (k: string) => { store.delete(k); },
+ platformSetStorageItem: (k: string, v: string) => {
+ if (faults.storeRefuses) throw new Error('QuotaExceededError');
+ if (!faults.storeDrops) store.set(k, v);
+ },
+ platformWriteCacheFile: vi.fn(async (k: string, b: ArrayBuffer) => {
+ if (faults.noCache) return 'unsupported';
+ if (faults.cacheRefuses) return 'failed';
+ cache.set(k, b);
+ return 'stored';
+ }),
+}));
+
+beforeEach(() => {
+ Object.assign(faults, { storeRefuses: false, storeDrops: false, cacheRefuses: false, noCache: false });
+ store.clear();
+ cache.clear();
+});
+
+/** One remote asset whose bytes are @p fill repeated 8 times. */
+function manifest(fill: number, revision: string): AddressableManifest {
+ const hash = contentHashHex(new Uint8Array(8).fill(fill));
+ return {
+ version: '2.0', revision,
+ groups: { cdn: { bundleMode: 'remote', labels: [], assets: {
+ 'uuid-1': { path: `assets/${hash}.png`, type: 'texture', size: 8, labels: [], contentHash: hash },
+ } } },
+ };
+}
+
+/** A CDN that serves the manifests by url and the bytes for whichever hash is asked;
+ * `hold` makes downloads wait until released. */
+function cdn(manifests: Record<string, AddressableManifest>) {
+ let release: () => void = () => {};
+ let gate: Promise<void> | null = null;
+ const fills = new Map<string, number>();
+ for (let fill = 0; fill < 16; fill++) fills.set(contentHashHex(new Uint8Array(8).fill(fill)), fill);
+ const backend = {
+ fetchBinary: vi.fn(async (url: string) => {
+ if (gate) await gate;
+ const hash = /assets\/(\w+)\.png/.exec(url)![1];
+ return new Uint8Array(8).fill(fills.get(hash) ?? 0).buffer;
+ }),
+ fetchText: vi.fn(async (url: string) => JSON.stringify(manifests[url])),
+ resolveUrl: vi.fn((p: string) => p),
+ } as any as Backend;
+ return {
+ backend,
+ hold() { gate = new Promise((r) => { release = () => { gate = null; r(); }; }); },
+ release: () => release(),
+ };
+}
+
+const KEY = 'hotupdate:test';
+
+function boot(backend: Backend): Assets {
+ const assets = Assets.create({ backend, catalog: Catalog.empty(), module: mockModule });
+ assets.setManifest(manifest(1, 'rev-1'));
+ assets.setRemoteRoot('https://cdn/v1');
+ assets.restorePersistedUpdate(KEY);
+ return assets;
+}
+
+/** What the next launch starts on, from a package that shipped @p shipped. */
+function relaunch(shipped = manifest(1, 'rev-1')): string | null {
+ const assets = Assets.create({ backend: cdn({}).backend, catalog: Catalog.empty(), module: mockModule });
+ assets.setManifest(shipped);
+ assets.restorePersistedUpdate(KEY);
+ return assets.getManifest()?.revision() ?? null;
+}
+
+describe('a hot update says which stages it reached', () => {
+ it('all four, when nothing refuses', async () => {
+ const assets = boot(cdn({ m2: manifest(2, 'rev-2') }).backend);
+ await assets.checkForUpdate({ manifestUrl: 'm2', remoteRoot: 'https://cdn/v2' });
+ const r = await assets.applyUpdate();
+ expect(r.stages).toEqual({ verified: true, applied: true, persisted: true, cached: true });
+ expect(r.revision).toBe('rev-2');
+ expect(relaunch()).toBe('rev-2');
+ });
+
+ it('not persisted when the store throws — and the next launch is on the old version, as it says', async () => {
+ const assets = boot(cdn({ m2: manifest(2, 'rev-2') }).backend);
+ await assets.checkForUpdate({ manifestUrl: 'm2', remoteRoot: 'https://cdn/v2' });
+ faults.storeRefuses = true;
+ const r = await assets.applyUpdate();
+ expect(r.ok).toBe(true);
+ expect(r.stages.applied).toBe(true);
+ expect(r.stages.persisted).toBe(false);
+ expect(relaunch()).toBe('rev-1');
+ });
+
+ it('not persisted when the store drops the write without throwing', async () => {
+ const assets = boot(cdn({ m2: manifest(2, 'rev-2') }).backend);
+ await assets.checkForUpdate({ manifestUrl: 'm2', remoteRoot: 'https://cdn/v2' });
+ faults.storeDrops = true;
+ expect((await assets.applyUpdate()).stages.persisted).toBe(false);
+ expect(relaunch()).toBe('rev-1');
+ });
+
+ it('not cached when the cache refuses, naming what the next launch will fetch again', async () => {
+ const assets = boot(cdn({ m2: manifest(2, 'rev-2') }).backend);
+ await assets.checkForUpdate({ manifestUrl: 'm2', remoteRoot: 'https://cdn/v2' });
+ faults.cacheRefuses = true;
+ const r = await assets.applyUpdate();
+ expect(r.stages.cached).toBe(false);
+ expect(r.uncached).toEqual([expect.stringMatching(/^https:\/\/cdn\/v2\/assets\/\w+\.png$/)]);
+ });
+
+ it('cached is unknown, not true, where the platform keeps no cache', async () => {
+ const assets = boot(cdn({ m2: manifest(2, 'rev-2') }).backend);
+ await assets.checkForUpdate({ manifestUrl: 'm2', remoteRoot: 'https://cdn/v2' });
+ faults.noCache = true;
+ expect((await assets.applyUpdate()).stages.cached).toBeNull();
+ });
+
+ it('nothing but verified=false when a download fails, and the next launch is untouched', async () => {
+ const c = cdn({ m2: manifest(2, 'rev-2') });
+ const assets = boot(c.backend);
+ await assets.checkForUpdate({ manifestUrl: 'm2', remoteRoot: 'https://cdn/v2' });
+ (c.backend.fetchBinary as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('offline'));
+ const r = await assets.applyUpdate();
+ expect(r.stages).toEqual({ verified: false, applied: false, persisted: false, cached: false });
+ expect(assets.getManifest()?.revision()).toBe('rev-1');
+ expect(relaunch()).toBe('rev-1');
+ });
+});
+
+describe('updates that overlap', () => {
+ it('an update found while another downloads is still there to apply afterwards', async () => {
+ const c = cdn({ m2: manifest(2, 'rev-2'), m3: manifest(3, 'rev-3') });
+ const assets = boot(c.backend);
+ await assets.checkForUpdate({ manifestUrl: 'm2', remoteRoot: 'https://cdn/v2' });
+ c.hold();
+ const first = assets.applyUpdate();
+ await assets.checkForUpdate({ manifestUrl: 'm3', remoteRoot: 'https://cdn/v3' });
+ c.release();
+ expect((await first).revision).toBe('rev-2');
+ const second = await assets.applyUpdate();
+ expect(second.ok).toBe(true);
+ expect(second.revision).toBe('rev-3');
+ expect(relaunch()).toBe('rev-3');
+ });
+
+ it('the later update is diffed against the version the earlier one committed', async () => {
+ const c = cdn({ m2: manifest(2, 'rev-2'), m3: manifest(2, 'rev-3') });
+ const assets = boot(c.backend);
+ await assets.checkForUpdate({ manifestUrl: 'm2', remoteRoot: 'https://cdn/v2' });
+ c.hold();
+ const first = assets.applyUpdate();
+ await assets.checkForUpdate({ manifestUrl: 'm3', remoteRoot: 'https://cdn/v2' });
+ c.release();
+ await first;
+ const calls = (c.backend.fetchBinary as ReturnType<typeof vi.fn>).mock.calls.length;
+ const second = await assets.applyUpdate();
+ expect(second.updated).toBe(0);
+ expect((c.backend.fetchBinary as ReturnType<typeof vi.fn>).mock.calls.length).toBe(calls);
+ });
+
+ it('applying twice at once downloads once and commits once', async () => {
+ const c = cdn({ m2: manifest(2, 'rev-2') });
+ const assets = boot(c.backend);
+ await assets.checkForUpdate({ manifestUrl: 'm2', remoteRoot: 'https://cdn/v2' });
+ const commits: string[] = [];
+ assets.onInvalidate((e) => commits.push(e.ref));
+ const [a, b] = await Promise.all([assets.applyUpdate(), assets.applyUpdate()]);
+ expect(a.ok).toBe(true);
+ expect(b.ok).toBe(false);
+ expect(b.reason).toBe('nothing-staged');
+ expect(commits).toEqual(['uuid-1']);
+ expect(c.backend.fetchBinary).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('what an update is doing right now', () => {
+ it('names the running, stored and staged revisions and what the staged one costs', async () => {
+ const assets = boot(cdn({ m2: manifest(2, 'rev-2') }).backend);
+ expect(assets.updateStatus()).toMatchObject({ revision: 'rev-1', persistedRevision: null, staged: null, applying: false });
+ await assets.checkForUpdate({ manifestUrl: 'm2', remoteRoot: 'https://cdn/v2' });
+ expect(assets.updateStatus().staged).toEqual({ revision: 'rev-2', assets: 1, bytes: 8 });
+ const applying = assets.applyUpdate();
+ expect(assets.updateStatus().applying).toBe(true);
+ await applying;
+ expect(assets.updateStatus()).toMatchObject({ revision: 'rev-2', persistedRevision: 'rev-2', staged: null, applying: false });
+ });
+});
+
+describe('a stored update belongs to the package it was applied to', () => {
+ it('is dropped when the package itself changed, rather than covering the newer content', async () => {
+ const assets = boot(cdn({ m2: manifest(2, 'rev-2') }).backend);
+ await assets.checkForUpdate({ manifestUrl: 'm2', remoteRoot: 'https://cdn/v2' });
+ await assets.applyUpdate();
+ expect(relaunch()).toBe('rev-2');
+ expect(relaunch(manifest(5, 'rev-5'))).toBe('rev-5');
+ expect(store.has(KEY)).toBe(false);
+ });
+
+ it('from before this rule is dropped too: which package it belonged to is unknown', () => {
+ store.set(KEY, JSON.stringify({ manifest: manifest(2, 'rev-2'), remoteRoot: 'https://cdn/v2' }));
+ expect(relaunch()).toBe('rev-1');
+ });
+});
+
diff --git a/sdk/tests/hot-update-runtime.test.ts b/sdk/tests/hot-update-runtime.test.ts
index f606b565d..d26091ce7 100644
--- a/sdk/tests/hot-update-runtime.test.ts
+++ b/sdk/tests/hot-update-runtime.test.ts
@@ -38,7 +38,8 @@ vi.mock('../src/platform', () => {
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(); }),
+ platformRemoveStorageItem: (k: string) => { store.delete(k); },
+ platformWriteCacheFile: vi.fn((k: string, b: ArrayBuffer) => { cache.set(k, b); return Promise.resolve('stored'); }),
__store: store,
__cache: cache,
};
@@ -279,7 +280,8 @@ describe('Assets.checkForUpdate / applyUpdate', () => {
const progress: [number, number][] = [];
const result = await assets.applyUpdate((loaded, total) => progress.push([loaded, total]));
- expect(result).toEqual({ ok: true, updated: 1, failed: [] });
+ expect(result).toMatchObject({ ok: true, updated: 1, failed: [], revision: 'rev-2' });
+ expect(result.stages).toEqual({ verified: true, applied: true, persisted: null, cached: true });
// Manifest + root are now the update's.
expect(assets.getManifest()?.revision()).toBe('rev-2');
expect(assets.remoteRoot).toBe('https://cdn/v2');
@@ -396,6 +398,7 @@ describe('Assets.restorePersistedUpdate', () => {
// A returning player boots a fresh Assets straight onto the updated manifest.
const second = createAssets(backendServing());
+ second.setManifest(cdnManifest('aaaa', 'rev-1'));
const restored = second.restorePersistedUpdate('hotupdate:demo');
expect(restored).toBe(true);
expect(second.getManifest()?.revision()).toBe('rev-2');
diff --git a/tools/launchers/headless-hotupdate-verify.mjs b/tools/launchers/headless-hotupdate-verify.mjs
index 5b7fb3933..19287fb55 100644
--- a/tools/launchers/headless-hotupdate-verify.mjs
+++ b/tools/launchers/headless-hotupdate-verify.mjs
@@ -154,10 +154,24 @@ app.whenReady().then(async () => {
});
}
- const ok = isGreen(before) && isRed(after) && changed >= 1 && refused.every((r) => r.ok);
+ // The stages a browser can honestly claim: stored in localStorage and read
+ // back, and no disk cache to have put anything in.
+ const stagesOk = good?.stages?.verified === true && good.stages.applied === true
+ && good.stages.persisted === true && good.stages.cached === null;
+ // A relaunch starts on the update, not on what shipped: the whole point of
+ // persisting it. The refused updates in between must not have displaced it.
+ await win.loadURL(`${base}/index.html?headless=1`);
+ let back = false;
+ for (let i = 0; i < 150 && !back; i++) { back = await exec('!!window.__estellaCooked').catch(() => false); if (!back) await sleep(100); }
+ await sleep(1800);
+ const relaunched = { pixel: await exec(center), status: await exec('window.__estellaCooked.updateStatus()') };
+ const relaunchOk = isRed(relaunched.pixel) && relaunched.status?.revision === good?.revision
+ && relaunched.status?.persistedRevision === good?.revision;
+
+ const ok = isGreen(before) && isRed(after) && changed >= 1 && refused.every((r) => r.ok) && stagesOk && relaunchOk;
console.log(`\n[verify:render:hotupdate] ${ok ? 'PASS' : 'FAIL'}`);
- console.log('DRIVE_RESULT ' + JSON.stringify({ before, after, changed, good, greenBefore: isGreen(before), redAfter: isRed(after), refused, diag: diag.slice(0, 8) }));
+ console.log('DRIVE_RESULT ' + JSON.stringify({ before, after, changed, good, greenBefore: isGreen(before), redAfter: isRed(after), refused, stagesOk, relaunched, relaunchOk, diag: diag.slice(0, 8) }));
failed = !ok;
} catch (e) {
console.log('\n[verify:render:hotupdate] FAIL — ' + (e?.message ?? e));