- | {communityText('Date')} | {communityText('Uploads')} | {communityText('Updates')} | {communityText('Users')} | {communityText('Sessions')} | {communityText('Loads')} | {communityText('Average load')} | {communityText('Samples')} | {communityText('Starts')} | {communityText('Crashes')} |
+ | {communityText('Date')} | {communityText('Uploads')} | {communityText('Updates')} | {communityText('Users')} | {communityText('Sessions')} | {communityText('Loads')} | {communityText('95th percentile load')} | {communityText('Samples')} | {communityText('Starts')} | {communityText('Crashes')} |
{dailyRows.map(row => (
- | {row.date} | {num(row.projects)} | {num(row.updates)} | {num(row.users)} | {num(row.sessions)} | {num(row.loads)} | {row.loadSamples ? formatLoadTime(row.averageLoadMs) : communityText('No sample')} | {num(row.loadSamples)} | {num(row.starts)} | {num(row.crashes)} |
+ {row.date} | {num(row.projects)} | {num(row.updates)} | {num(row.users)} | {num(row.sessions)} | {num(row.loads)} | {row.loadSamples ? formatLoadTime(row.p95LoadMs) : communityText('No sample')} | {num(row.loadSamples)} | {num(row.starts)} | {num(row.crashes)} |
))}
diff --git a/src/community/pages/project/ProjectPreview.jsx b/src/community/pages/project/ProjectPreview.jsx
index cc61be36d8b..4fb45da3837 100644
--- a/src/community/pages/project/ProjectPreview.jsx
+++ b/src/community/pages/project/ProjectPreview.jsx
@@ -18,10 +18,10 @@ const ProjectPreview = ({project}) => {
const bridged = playing ? project : null;
useEmbedFetchBridge(bridged, frame);
useEmbedStorageBridge(bridged, frame);
- const {id, projectJsonUrl, assetsBase} = project;
+ const {id, projectJsonUrl, assetsBase, assetsMirrorBase} = project;
const src = useMemo(
() => (playing ? embedUrl(project, {applyProjectTheme: false, persistStorage: true}) : ''),
- [playing, id, projectJsonUrl, assetsBase]
+ [playing, id, projectJsonUrl, assetsBase, assetsMirrorBase]
);
useEffect(() => {
if (!playing) return;
@@ -78,6 +78,7 @@ const ProjectPreview = ({project}) => {
ProjectPreview.propTypes = {
project: PropTypes.shape({
assetsBase: PropTypes.string,
+ assetsMirrorBase: PropTypes.string,
hasContent: PropTypes.bool,
id: PropTypes.string,
projectJsonUrl: PropTypes.string,
diff --git a/src/community/pages/project/use-embed-bridges.js b/src/community/pages/project/use-embed-bridges.js
index 17ecc21eaa6..7bb722bd831 100644
--- a/src/community/pages/project/use-embed-bridges.js
+++ b/src/community/pages/project/use-embed-bridges.js
@@ -8,9 +8,11 @@ export const useEmbedFetchBridge = (project, stageFrame) => {
useEffect(() => {
if (!project || !project.projectJsonUrl) return;
preloadContent(project.projectJsonUrl).catch(() => null);
- const assetsBase = project.assetsBase ? `${project.assetsBase.replace(/\/+$/, '')}/` : null;
- const allowed = url => typeof url === 'string' &&
- (url === project.projectJsonUrl || (assetsBase && url.startsWith(assetsBase)));
+ const assetBases = [project.assetsBase, project.assetsMirrorBase]
+ .filter(base => typeof base === 'string' && base)
+ .map(base => `${base.replace(/\/+$/, '')}/`);
+ const isAsset = url => assetBases.some(base => url.startsWith(base));
+ const allowed = url => typeof url === 'string' && (url === project.projectJsonUrl || isAsset(url));
const onMessage = event => {
const frame = stageFrame.current;
if (!frame || event.source !== frame.contentWindow) return;
@@ -41,7 +43,7 @@ export const useEmbedFetchBridge = (project, stageFrame) => {
// ignore
}
};
- cachedFetchBuffer(data.url)
+ cachedFetchBuffer(data.url, {immutable: isAsset(data.url)})
.then(buffer => {
const copy = buffer.slice(0);
reply({type: 'mw:fetch-result', id: data.id, buffer: copy}, [copy]);
diff --git a/src/community/translations/_sources.json b/src/community/translations/_sources.json
index 62570009226..e0061087469 100644
--- a/src/community/translations/_sources.json
+++ b/src/community/translations/_sources.json
@@ -12,8 +12,8 @@
"src/community/api-errors.js:31",
"src/community/components/ui/EmptyState.jsx:36",
"src/community/rotur.js:59",
- "src/community/rotur.js:148",
- "src/community/rotur.js:155"
+ "src/community/rotur.js:149",
+ "src/community/rotur.js:156"
],
"You don't have permission to do that.": [
"src/community/api-errors.js:32"
@@ -1094,7 +1094,7 @@
"src/community/pages/ManageSpace.jsx:822",
"src/community/pages/MyStuff.jsx:1325",
"src/community/pages/MyStuff.jsx:1341",
- "src/community/pages/Project.jsx:724",
+ "src/community/pages/Project.jsx:725",
"src/community/pages/Settings.jsx:1003",
"src/community/pages/Settings.jsx:1018",
"src/community/pages/Theme.jsx:239",
@@ -2735,7 +2735,7 @@
"Updated {value1}": [
"src/community/components/NewsItem.jsx:205",
"src/community/pages/NewsPost.jsx:136",
- "src/community/pages/Project.jsx:824",
+ "src/community/pages/Project.jsx:825",
"src/community/pages/ProjectCode.jsx:118"
],
"Post analytics": [
@@ -7175,7 +7175,7 @@
"{value1} ms": [
"src/community/pages/ManageProject.jsx:827"
],
- "Average load": [
+ "95th percentile load": [
"src/community/pages/ManageProject.jsx:827",
"src/community/pages/admin/StatsOverview.jsx:527"
],
@@ -8427,42 +8427,42 @@
"src/community/pages/Project.jsx:604"
],
"Delete project?": [
- "src/community/pages/Project.jsx:721",
+ "src/community/pages/Project.jsx:722",
"src/community/pages/admin/ProjectManager.jsx:68",
"src/community/pages/admin/UserDetailCard.jsx:253"
],
"Delete project": [
- "src/community/pages/Project.jsx:722",
+ "src/community/pages/Project.jsx:723",
"src/community/pages/admin/ProjectManager.jsx:70",
"src/community/pages/admin/UserDetailCard.jsx:255",
"src/community/pages/project/ProjectHeader.jsx:361"
],
"{value1} will be deleted permanently. This cannot be undone.": [
- "src/community/pages/Project.jsx:728"
+ "src/community/pages/Project.jsx:729"
],
"Run custom extensions without the sandbox?": [
- "src/community/pages/Project.jsx:734"
+ "src/community/pages/Project.jsx:735"
],
"Keep sandbox": [
- "src/community/pages/Project.jsx:735"
+ "src/community/pages/Project.jsx:736"
],
"Run anyway": [
- "src/community/pages/Project.jsx:736"
+ "src/community/pages/Project.jsx:737"
],
"This gives the project full access to your MistWarp account. It could read your login session, act as you, or change your data. Continue only if you trust the creator.": [
- "src/community/pages/Project.jsx:739"
+ "src/community/pages/Project.jsx:740"
],
"Shared {value1}": [
- "src/community/pages/Project.jsx:816",
+ "src/community/pages/Project.jsx:817",
"src/community/pages/admin/UserDetailCard.jsx:323",
"src/community/pages/project/ProjectHeader.jsx:97"
],
"Uploaded {value1}": [
- "src/community/pages/Project.jsx:817",
+ "src/community/pages/Project.jsx:818",
"src/community/pages/project/ProjectHeader.jsx:98"
],
"{value1} blocks": [
- "src/community/pages/Project.jsx:830"
+ "src/community/pages/Project.jsx:831"
],
"About this project": [
"src/community/pages/ProjectCode.jsx:75"
@@ -10601,7 +10601,7 @@
"{value1} of {value2} projects": [
"src/community/pages/admin/StatsOverview.jsx:398"
],
- "Average load, {value1} days": [
+ "95th percentile load, {value1} days": [
"src/community/pages/admin/StatsOverview.jsx:401"
],
"{value1} completed samples": [
@@ -10658,10 +10658,10 @@
"Dashed lines estimate today's UTC close from its current pace and the prior seven days.": [
"src/community/pages/admin/StatsOverview.jsx:454"
],
- "Average project load time": [
+ "Project load time, 95th percentile": [
"src/community/pages/admin/StatsOverview.jsx:458"
],
- "{value1} completed player loads in this period. Days without a sample appear as gaps.": [
+ "95% of timed player loads each day finished within this time. Days without a sample appear as gaps.": [
"src/community/pages/admin/StatsOverview.jsx:459"
],
"Milliseconds": [
@@ -10704,7 +10704,7 @@
"Daily data": [
"src/community/pages/admin/StatsOverview.jsx:510"
],
- "Exact values behind the charts. Load averages only use completed loads with a recorded duration.": [
+ "Exact values behind the charts. Load times only use completed loads with a recorded duration.": [
"src/community/pages/admin/StatsOverview.jsx:511"
],
"Hide data": [
@@ -11639,7 +11639,7 @@
],
"MistWarp needs your permission on Rotur to do this.": [
"src/community/rotur.js:52",
- "src/community/rotur.js:157"
+ "src/community/rotur.js:158"
],
"This remix changed while it was syncing. Sync again to include the new changes.": [
"src/community/use-remix-sync.js:47"
diff --git a/src/community/translations/en.json b/src/community/translations/en.json
index 44a3016a458..fd5287b88ff 100644
--- a/src/community/translations/en.json
+++ b/src/community/translations/en.json
@@ -428,7 +428,6 @@
"Recorded playtime": "Recorded playtime",
"Trends": "Trends",
"Dashed lines estimate today's UTC close from its current pace and the prior seven days.": "Dashed lines estimate today's UTC close from its current pace and the prior seven days.",
- "Average project load time": "Average project load time",
"Project uploads": "Project uploads",
"Projects created each day, including shared and unshared projects.": "Projects created each day, including shared and unshared projects.",
"Project updates": "Project updates",
@@ -440,7 +439,6 @@
"Current sessions by sign-in date": "Current sessions by sign-in date",
"Unexpired sign-in sessions only. MistWarp removes sessions after seven days.": "Unexpired sign-in sessions only. MistWarp removes sessions after seven days.",
"Daily data": "Daily data",
- "Exact values behind the charts. Load averages only use completed loads with a recorded duration.": "Exact values behind the charts. Load averages only use completed loads with a recorded duration.",
"Hide data": "Hide data",
"View data": "View data",
"Download CSV": "Download CSV",
@@ -448,7 +446,6 @@
"Updates": "Updates",
"Sessions": "Sessions",
"Loads": "Loads",
- "Average load": "Average load",
"Samples": "Samples",
"Starts": "Starts",
"Crashes": "Crashes",
@@ -1350,8 +1347,6 @@
"{value1} composition": "{value1} composition",
"Estimated end of today: {value1}": "Estimated end of today: {value1}",
"{value1} days": "{value1} days",
- "Average load, {value1} days": "Average load, {value1} days",
- "{value1} completed player loads in this period. Days without a sample appear as gaps.": "{value1} completed player loads in this period. Days without a sample appear as gaps.",
"by @{value1} · {value2}": "by @{value1} · {value2}",
"{value1} of {value2}": "{value1} of {value2}",
"{value1}–{value2} of {value3}": "{value1}–{value2} of {value3}",
@@ -3839,5 +3834,10 @@
"Only an admin of @{org} can move this space out of the organisation.": "Only an admin of @{org} can move this space out of the organisation.",
"Could not load your organisations, so this space will be yours.": "Could not load your organisations, so this space will be yours.",
"Transfer \"{space}\" to @{owner}? The organisation will no longer own it.": "Transfer \"{space}\" to @{owner}? The organisation will no longer own it.",
- "The new owner receives this {value1}. The organisation will no longer own it.": "The new owner receives this {value1}. The organisation will no longer own it."
+ "The new owner receives this {value1}. The organisation will no longer own it.": "The new owner receives this {value1}. The organisation will no longer own it.",
+ "95th percentile load": "95th percentile load",
+ "95th percentile load, {value1} days": "95th percentile load, {value1} days",
+ "Project load time, 95th percentile": "Project load time, 95th percentile",
+ "Exact values behind the charts. Load times only use completed loads with a recorded duration.": "Exact values behind the charts. Load times only use completed loads with a recorded duration.",
+ "95% of timed player loads each day finished within this time. Days without a sample appear as gaps.": "95% of timed player loads each day finished within this time. Days without a sample appear as gaps."
}
diff --git a/src/lib/community/cached-fetch.js b/src/lib/community/cached-fetch.js
index 7979e860012..fe0a14f8ace 100644
--- a/src/lib/community/cached-fetch.js
+++ b/src/lib/community/cached-fetch.js
@@ -42,7 +42,7 @@ const readProjectResponse = async response => {
return buffer;
};
-const fetchAndStore = async url => {
+const fetchAndStore = async (url, immutable) => {
const generation = cacheGeneration;
const cache = await openCache();
let cachedHit = null;
@@ -58,7 +58,7 @@ const fetchAndStore = async url => {
throw new Error('Discarding cached HTML project response');
}
const at = Number(getHeader(hit.headers, CACHED_AT_HEADER));
- if (at && Date.now() - at < TTL) {
+ if (immutable || (at && Date.now() - at < TTL)) {
return buffer;
}
storedEtag = getHeader(hit.headers, ETAG_HEADER) || getHeader(hit.headers, 'etag');
@@ -138,10 +138,10 @@ const fetchAndStore = async url => {
return buffer;
};
-const sharedFetch = url => {
+const sharedFetch = (url, immutable = false) => {
let promise = inflight.get(url);
if (!promise) {
- promise = fetchAndStore(url);
+ promise = fetchAndStore(url, immutable);
inflight.set(url, promise);
const remove = () => {
if (inflight.get(url) === promise) inflight.delete(url);
@@ -151,7 +151,7 @@ const sharedFetch = url => {
return promise;
};
-const cachedFetchBuffer = url => {
+const cachedFetchBuffer = (url, {immutable = false} = {}) => {
const warmed = preloaded.get(url);
if (warmed && Date.now() - warmed.at < PRELOAD_TTL) {
preloaded.delete(url);
@@ -160,7 +160,7 @@ const cachedFetchBuffer = url => {
if (warmed) preloaded.delete(url);
// Project consumers treat the downloaded bytes as immutable. Returning the
// shared buffer avoids copying the entire project before JSZip reads it.
- return sharedFetch(url);
+ return sharedFetch(url, immutable);
};
const cachedFetchJson = url => sharedFetch(url)
diff --git a/src/lib/components/project-fetcher-hoc.jsx b/src/lib/components/project-fetcher-hoc.jsx
index a507452f351..5cbf8d0225b 100644
--- a/src/lib/components/project-fetcher-hoc.jsx
+++ b/src/lib/components/project-fetcher-hoc.jsx
@@ -113,7 +113,8 @@ const clearProjectSourceFromUrl = () => {
const params = new URLSearchParams(location.search);
let changed = false;
const sourceKeys = [
- 'clone', 'project_url', 'platform_project', 'mw_assets', 'mw_te', 'starter', 'restore', 'from'
+ 'clone', 'project_url', 'platform_project', 'mw_assets', 'mw_assets_mirror', 'mw_te', 'starter', 'restore',
+ 'from'
];
for (const key of sourceKeys) {
if (params.has(key)) {
@@ -338,8 +339,10 @@ const ProjectFetcherHOC = function (WrappedComponent) {
location.hash.match(/^#mw-([\w-]+)/);
const hashProjectId = hashMatch && hashMatch[1];
const mistwarpAssets = !student && searchParams && searchParams.get('mw_assets');
+ const mirrorParam = mistwarpAssets && searchParams.get('mw_assets_mirror');
+ const assetsMirror = mirrorParam && isHttpUrl(mirrorParam) ? mirrorParam : null;
if (mistwarpAssets && isHttpUrl(mistwarpAssets)) {
- storage.addMistWarpAssetStore(mistwarpAssets);
+ storage.addMistWarpAssetStore(mistwarpAssets, assetsMirror);
}
let projectUrl = searchParams && searchParams.get('project_url');
if (student && !isGallerySampleUrl(projectUrl)) projectUrl = null;
@@ -351,7 +354,8 @@ const ProjectFetcherHOC = function (WrappedComponent) {
const source = this.props.isEmbedded && platformProject && !hashProjectId && projectUrl ? {
id,
projectJsonUrl: projectUrl,
- assetsBase: mistwarpAssets
+ assetsBase: mistwarpAssets,
+ assetsMirrorBase: assetsMirror
} : null;
assetPromise = loadPlatformProject(id, source);
} else if (cloneUrl) {
@@ -429,7 +433,10 @@ const ProjectFetcherHOC = function (WrappedComponent) {
if (projectAsset.platformProject) {
const project = projectAsset.platformProject;
if (project.assetsBase && isHttpUrl(project.assetsBase)) {
- storage.addMistWarpAssetStore(project.assetsBase);
+ const mirror = project.assetsMirrorBase && isHttpUrl(project.assetsMirrorBase) ?
+ project.assetsMirrorBase :
+ null;
+ storage.addMistWarpAssetStore(project.assetsBase, mirror);
}
rememberPlatformProject(project, {resetSaveBase: true});
await deleteRepo();
diff --git a/src/lib/persistence/storage.js b/src/lib/persistence/storage.js
index 89d350e00b6..2ffbc6683c5 100644
--- a/src/lib/persistence/storage.js
+++ b/src/lib/persistence/storage.js
@@ -42,30 +42,31 @@ class Storage extends ScratchStorage {
this.getAssetCreateConfig.bind(this)
);
}
- addMistWarpAssetStore (assetsBase) {
+ addMistWarpAssetStore (assetsBase, mirrorBase) {
const base = assetsBase.replace(/\/+$/, '');
- if (this.mistwarpAssetsBase === base) {
- return;
- }
+ const mirror = mirrorBase ? mirrorBase.replace(/\/+$/, '') : null;
if (this.mistwarpAssetsBase) {
this.mistwarpAssetsBase = base;
+ this.mistwarpAssetsMirror = mirror;
return;
}
this.mistwarpAssetsBase = base;
- if (hasBridge()) {
- this.addHelper({
- load: (assetType, assetId, dataFormat) =>
- bridgeFetch(`${this.mistwarpAssetsBase}/${assetId}.${dataFormat}`)
- .then(buffer => this.createAsset(assetType, dataFormat, new Uint8Array(buffer), assetId))
- });
- } else {
- this.addHelper({
- load: (assetType, assetId, dataFormat) =>
- cachedFetchBuffer(`${this.mistwarpAssetsBase}/${assetId}.${dataFormat}`)
- .then(buffer => this.createAsset(assetType, dataFormat, new Uint8Array(buffer), assetId))
- .catch(() => null)
- });
- }
+ this.mistwarpAssetsMirror = mirror;
+ const fetchAsset = hasBridge() ?
+ url => bridgeFetch(url) :
+ url => cachedFetchBuffer(url, {immutable: true});
+ const fetchFromStores = file => {
+ const primary = `${this.mistwarpAssetsBase}/${file}`;
+ if (!this.mistwarpAssetsMirror) return fetchAsset(primary);
+ return fetchAsset(`${this.mistwarpAssetsMirror}/${file}`).catch(() => fetchAsset(primary));
+ };
+ const loading = (assetType, assetId, dataFormat) => fetchFromStores(`${assetId}.${dataFormat}`)
+ .then(buffer => this.createAsset(assetType, dataFormat, new Uint8Array(buffer), assetId));
+ this.addHelper({
+ load: hasBridge() ?
+ loading :
+ (assetType, assetId, dataFormat) => loading(assetType, assetId, dataFormat).catch(() => null)
+ });
this.addWebStore(
[
this.AssetType.ImageVector,
diff --git a/src/playground/embed.jsx b/src/playground/embed.jsx
index 854287a0722..65fd38902b6 100644
--- a/src/playground/embed.jsx
+++ b/src/playground/embed.jsx
@@ -44,6 +44,11 @@ window.addEventListener('message', applyEmbedThemeMessage);
const urlParams = new URLSearchParams(location.search);
const projectId = urlParams.get('platform_project') || getProjectId();
const sessionStartedAt = performance.now();
+let hiddenDuringLoad = document.visibilityState === 'hidden';
+const noteHiddenDuringLoad = () => {
+ if (document.visibilityState === 'hidden') hiddenDuringLoad = true;
+};
+document.addEventListener('visibilitychange', noteHiddenDuringLoad);
let playing = false;
const LINK_BACK_REFS = new Set(['embed', 'oembed']);
const linkBack = urlParams.get('mw_public') === '1' ? document.createElement('a') : null;
@@ -117,9 +122,10 @@ const onVmInit = _vm => {
};
const onProjectLoaded = () => {
+ document.removeEventListener('visibilitychange', noteHiddenDuringLoad);
reportDiagnostic({
type: 'load',
- loadMs: Math.round(performance.now() - sessionStartedAt),
+ loadMs: hiddenDuringLoad ? 0 : Math.round(performance.now() - sessionStartedAt),
device: matchMedia('(pointer: coarse)').matches ? 'touch' : 'desktop'
});
if (window.parent !== window && vm && vm.runtime) {
diff --git a/test/unit/community-cached-fetch.test.js b/test/unit/community-cached-fetch.test.js
index 7fd53618839..81f0a2fab30 100644
--- a/test/unit/community-cached-fetch.test.js
+++ b/test/unit/community-cached-fetch.test.js
@@ -195,4 +195,31 @@ describe('community project content cache', () => {
expect(loaded).toBe(buffer);
expect(cache.put).toHaveBeenCalledTimes(1);
});
+
+ test('uses a cached immutable file without revalidating it', async () => {
+ const assetUrl = 'https://assets.example/0123456789abcdef0123456789abcdef.png';
+ const cached = new Uint8Array([7, 8, 9]).buffer;
+ const tenMinutesAgo = String(Date.now() - (10 * 60 * 1000));
+ global.caches.open = jest.fn(() => Promise.resolve({
+ match: jest.fn(() => Promise.resolve({
+ arrayBuffer: async () => cached,
+ headers: {get: name => (name === 'x-mw-cached-at' ? tenMinutesAgo : null)}
+ })),
+ put: jest.fn(() => Promise.resolve()),
+ delete: jest.fn(() => Promise.resolve())
+ }));
+
+ await expect(cachedFetchBuffer(assetUrl, {immutable: true})).resolves.toBe(cached);
+ expect(global.fetch).not.toHaveBeenCalled();
+
+ clearContentCache();
+ global.fetch.mockResolvedValue({
+ ok: true,
+ status: 200,
+ headers: {get: () => null},
+ arrayBuffer: async () => cached
+ });
+ await cachedFetchBuffer(assetUrl);
+ expect(global.fetch).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/test/unit/community-embed-fetch-bridge.test.jsx b/test/unit/community-embed-fetch-bridge.test.jsx
index 8c2b59d731f..7e363070184 100644
--- a/test/unit/community-embed-fetch-bridge.test.jsx
+++ b/test/unit/community-embed-fetch-bridge.test.jsx
@@ -9,7 +9,12 @@ jest.mock('../../src/lib/community/cached-fetch.js', () => ({
preloadContent: jest.fn(() => Promise.resolve(null))
}));
-const project = {id: '1', projectJsonUrl: 'https://cdn.test/project.sb3'};
+const project = {
+ id: '1',
+ projectJsonUrl: 'https://cdn.test/project.sb3',
+ assetsBase: 'https://api.test/blobs/assets',
+ assetsMirrorBase: 'https://r2.test/assets'
+};
const Bridge = ({frame}) => {
const ref = useRef(frame);
@@ -42,3 +47,34 @@ test('sends the player a copy of the cached project, not the cached buffer itsel
expect(transfer).toEqual([message.buffer]);
wrapper.unmount();
});
+
+const requestThroughBridge = async (frame, url) => {
+ await act(async () => {
+ window.dispatchEvent(new MessageEvent('message', {
+ source: frame.contentWindow,
+ data: {type: 'mw:fetch', id: 9, url}
+ }));
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+};
+
+test('serves mirrored and API assets from the cache without revalidating them', async () => {
+ cachedFetchBuffer.mockReset();
+ cachedFetchBuffer.mockResolvedValue(new Uint8Array([1]).buffer);
+ const postMessage = jest.fn();
+ const frame = {contentWindow: {postMessage}};
+ const wrapper = mount(
);
+
+ await requestThroughBridge(frame, 'https://r2.test/assets/0123456789abcdef0123456789abcdef.png');
+ await requestThroughBridge(frame, 'https://api.test/blobs/assets/0123456789abcdef0123456789abcdef.png');
+ await requestThroughBridge(frame, project.projectJsonUrl);
+ await requestThroughBridge(frame, 'https://elsewhere.test/assets/0123456789abcdef0123456789abcdef.png');
+
+ expect(cachedFetchBuffer.mock.calls).toEqual([
+ ['https://r2.test/assets/0123456789abcdef0123456789abcdef.png', {immutable: true}],
+ ['https://api.test/blobs/assets/0123456789abcdef0123456789abcdef.png', {immutable: true}],
+ [project.projectJsonUrl, {immutable: false}]
+ ]);
+ wrapper.unmount();
+});
diff --git a/test/unit/community-embed-url.test.js b/test/unit/community-embed-url.test.js
index 97d8c7e8beb..c78b415ca92 100644
--- a/test/unit/community-embed-url.test.js
+++ b/test/unit/community-embed-url.test.js
@@ -21,3 +21,20 @@ test('project embeds never carry a trusted extension list in the URL', () => {
}), window.location.origin);
expect(url.searchParams.has('mw_te')).toBe(false);
});
+
+test('project embeds pass the asset mirror when the API offers one', () => {
+ const withMirror = new URL(embedUrl({
+ id: 'project-1',
+ projectJsonUrl: 'https://api.example/project.json',
+ assetsBase: 'https://api.example/assets',
+ assetsMirrorBase: 'https://cdn.example/assets'
+ }), window.location.origin);
+ expect(withMirror.searchParams.get('mw_assets_mirror')).toBe('https://cdn.example/assets');
+
+ const withoutMirror = new URL(embedUrl({
+ id: 'project-1',
+ projectJsonUrl: 'https://api.example/project.json',
+ assetsBase: 'https://api.example/assets'
+ }), window.location.origin);
+ expect(withoutMirror.searchParams.has('mw_assets_mirror')).toBe(false);
+});
diff --git a/test/unit/mistwarp-asset-mirror.test.js b/test/unit/mistwarp-asset-mirror.test.js
new file mode 100644
index 00000000000..78ab7fc3405
--- /dev/null
+++ b/test/unit/mistwarp-asset-mirror.test.js
@@ -0,0 +1,55 @@
+import storage from '../../src/lib/persistence/storage';
+import {cachedFetchBuffer} from '../../src/lib/community/cached-fetch';
+
+jest.mock('../../src/lib/community/cached-fetch', () => ({
+ cachedFetchBuffer: jest.fn()
+}));
+
+jest.mock('../../src/lib/community/embed-bridge', () => ({
+ hasBridge: () => false,
+ bridgeFetch: jest.fn()
+}));
+
+const assetId = '0123456789abcdef0123456789abcdef';
+const bytes = new Uint8Array([137, 80, 78, 71]).buffer;
+
+const loadAsset = () => storage.load(storage.AssetType.ImageBitmap, assetId, 'png');
+
+beforeEach(() => {
+ cachedFetchBuffer.mockReset();
+});
+
+test('loads assets from the mirror without asking the API', async () => {
+ storage.addMistWarpAssetStore('https://api.test/blobs/assets', 'https://r2.test/assets/');
+ cachedFetchBuffer.mockResolvedValue(bytes);
+
+ const asset = await loadAsset();
+
+ expect(asset.assetId).toBe(assetId);
+ expect(cachedFetchBuffer).toHaveBeenCalledTimes(1);
+ expect(cachedFetchBuffer).toHaveBeenCalledWith(`https://r2.test/assets/${assetId}.png`, {immutable: true});
+});
+
+test('falls back to the API when the mirror does not have the asset yet', async () => {
+ storage.addMistWarpAssetStore('https://api.test/blobs/assets', 'https://r2.test/assets');
+ cachedFetchBuffer
+ .mockRejectedValueOnce(Object.assign(new Error('Request returned status 404'), {status: 404}))
+ .mockResolvedValueOnce(bytes);
+
+ const asset = await loadAsset();
+
+ expect(asset.assetId).toBe(assetId);
+ expect(cachedFetchBuffer.mock.calls.map(call => call[0])).toEqual([
+ `https://r2.test/assets/${assetId}.png`,
+ `https://api.test/blobs/assets/${assetId}.png`
+ ]);
+});
+
+test('uses only the API when no mirror is offered', async () => {
+ storage.addMistWarpAssetStore('https://api.test/blobs/assets', null);
+ cachedFetchBuffer.mockResolvedValue(bytes);
+
+ await loadAsset();
+
+ expect(cachedFetchBuffer.mock.calls.map(call => call[0])).toEqual([`https://api.test/blobs/assets/${assetId}.png`]);
+});
From 1f2a3c8b23b4fa96ec9c377ca0a593a011a71517 Mon Sep 17 00:00:00 2001
From: Mistium <92952823+Mistium@users.noreply.github.com>
Date: Mon, 30 Nov 2026 19:21:21 +0000
Subject: [PATCH 2/3] Pass the asset mirror to public embeds and tighten the
fetch bridge
Embeds opened with ?mw=
now carry the asset mirror too. The parent
page bridge compares origins and folder paths instead of string
prefixes, and only caches md5-named files as immutable. Detaching a
workspace also clears the mirror parameter, and the project diagnostics
card shows how many loads were timed.
---
src/community/pages/ManageProject.jsx | 1 +
.../pages/project/use-embed-bridges.js | 32 +++++-
src/community/translations/_sources.json | 101 +++++++++---------
src/community/translations/en.json | 3 +-
src/lib/workspace-state.js | 5 +-
src/playground/embed.jsx | 1 +
.../community-embed-fetch-bridge.test.jsx | 17 +++
test/unit/student-project-sources.test.jsx | 43 ++++++++
8 files changed, 148 insertions(+), 55 deletions(-)
diff --git a/src/community/pages/ManageProject.jsx b/src/community/pages/ManageProject.jsx
index 48b4e83c1da..4698dfe5a56 100644
--- a/src/community/pages/ManageProject.jsx
+++ b/src/community/pages/ManageProject.jsx
@@ -825,6 +825,7 @@ const ManageProject = () => {
{diagnostics.counts.start || 0}{communityText('Green flags')}
{diagnostics.counts.crash || 0}{communityText('Errors')}
{communityText('{value1} ms', {value1: Math.round(diagnostics.p95LoadMs || 0)})}{communityText('95th percentile load')}
+ {diagnostics.loadSamples || 0}{communityText('Timed loads')}
) : diagnosticsError ? (