36 lines
1.4 KiB
JavaScript
36 lines
1.4 KiB
JavaScript
// Creating several sessions at once temporarily retains several copies of the
|
|
// models and allocator workspaces. Keep every declared action, but load one at
|
|
// a time and roll back all sessions if startup fails.
|
|
export async function loadSessionsSequentially(entries, create, validate = async () => {}, progress = () => {}) {
|
|
const sessions = {};
|
|
try {
|
|
for (const [id, source] of entries) {
|
|
const session = await create(source);
|
|
sessions[id] = session;
|
|
await validate(session);
|
|
progress(Object.keys(sessions).length, entries.length);
|
|
}
|
|
return sessions;
|
|
} catch (error) {
|
|
await Promise.allSettled(Object.values(sessions).map((s) => s.release()));
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// Drop the JS download buffer after copying each asset into MuJoCo's VFS,
|
|
// instead of retaining a second complete copy of the package during compile.
|
|
export async function populateVfs(vfs, assets, fetchBytes, concurrency = 2) {
|
|
let next = 0, failure;
|
|
await Promise.all(Array.from({ length: Math.min(concurrency, assets.length) }, async () => {
|
|
while (!failure && next < assets.length) {
|
|
const asset = assets[next++];
|
|
try {
|
|
const bytes = await fetchBytes(asset);
|
|
if (!failure) vfs.addBuffer(asset.vfs, new Uint8Array(bytes));
|
|
} catch (error) { failure ??= error; }
|
|
}
|
|
}));
|
|
// All outstanding downloads have settled before the caller can delete VFS.
|
|
if (failure) throw failure;
|
|
}
|