Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(desktop): reduce core OTA packaging memory (#20349)

Inneiaaeb8fbc47dd
diff --git a/apps/desktop/scripts/__tests__/buildCoreManifest.test.mjs b/apps/desktop/scripts/__tests__/buildCoreManifest.test.mjs
index 40e097075b0..b58ccbf3a2c 100644
--- a/apps/desktop/scripts/__tests__/buildCoreManifest.test.mjs
+++ b/apps/desktop/scripts/__tests__/buildCoreManifest.test.mjs
@@ -15,6 +15,7 @@ import {
createCoreManifest,
PLACEHOLDER_FULL,
PLACEHOLDER_OBJECTS_BASE_URL,
+ readCoreTree,
} from '../buildCoreManifest.mjs';
const shellLoader = createRequire(import.meta.url)('../../shell/core-loader.js');
@@ -94,6 +95,21 @@ describe('buildCoreManifest', () => {
expect(JSON.parse(await readFile(path.join(root, 'manifest.json'), 'utf8'))).toEqual(manifest);
});
+ it('can index object paths without retaining the core contents', async () => {
+ await setup();
+ await writeFile(path.join(root, 'copy.js'), 'main');
+ await writeFile(path.join(root, '.DS_Store'), 'finder');
+ const buffered = readCoreTree(root);
+ const indexed = readCoreTree(root, { retainContents: false });
+
+ expect(indexed.tree).toEqual(buffered.tree);
+ expect(indexed.objects.size).toBe(buffered.objects.size);
+ for (const [hash, file] of indexed.objects) {
+ expect(typeof file).toBe('string');
+ expect(await readFile(file)).toEqual(buffered.objects.get(hash));
+ }
+ });
+
it('signs so the shell loader verifies, and rejects a tampered byte', async () => {
await setup();
const { privateKeyPem, publicKeyPem } = keys();
diff --git a/apps/desktop/scripts/__tests__/buildCoreV4.test.mjs b/apps/desktop/scripts/__tests__/buildCoreV4.test.mjs
new file mode 100644
index 00000000000..89afdfbf0eb
--- /dev/null
+++ b/apps/desktop/scripts/__tests__/buildCoreV4.test.mjs
@@ -0,0 +1,82 @@
+import { createHash } from 'node:crypto';
+import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { writeCorePack } from '../buildCoreV4.mjs';
+
+const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
+let output;
+beforeEach(async () => {
+ output = await mkdtemp(path.join(tmpdir(), 'core-pack-'));
+});
+afterEach(async () => {
+ await rm(output, { force: true, recursive: true });
+});
+
+describe('writeCorePack', () => {
+ it('writes lazy frames with the same sorted bytes, hashes and offsets as buffered frames', async () => {
+ const entries = new Map([
+ ['b', Buffer.from('second')],
+ ['a', Buffer.from('first')],
+ ]);
+ const buffered = await writeCorePack(entries, output);
+ const produced = [];
+ const lazy = await writeCorePack(
+ new Map(
+ [...entries].map(([key, bytes]) => [
+ key,
+ async () => {
+ produced.push(key);
+ return bytes;
+ },
+ ]),
+ ),
+ output,
+ );
+ const expected = Buffer.from('firstsecond');
+ expect(lazy).toEqual(buffered);
+ expect(produced).toEqual(['a', 'b']);
+ expect(await readFile(path.join(output, lazy.pack.path))).toEqual(expected);
+ expect(lazy.pack).toEqual({
+ path: `packs/${hash(expected)}.pack`,
+ sha256: hash(expected),
+ size: 11,
+ });
+ expect(lazy.index).toEqual({
+ a: {
+ compressedSha256: hash(Buffer.from('first')),
+ length: 5,
+ offset: 0,
+ packSha256: hash(expected),
+ },
+ b: {
+ compressedSha256: hash(Buffer.from('second')),
+ length: 6,
+ offset: 5,
+ packSha256: hash(expected),
+ },
+ });
+ expect(await readdir(path.join(output, 'packs'))).toEqual([`${hash(expected)}.pack`]);
+ });
+
+ it('removes partial packs when a frame producer fails', async () => {
+ await expect(
+ writeCorePack(
+ new Map([
+ ['a', Buffer.from('first')],
+ [
+ 'b',
+ async () => {
+ throw new Error('read failed');
+ },
+ ],
+ ]),
+ output,
+ ),
+ ).rejects.toThrow('read failed');
+ expect(await readdir(path.join(output, 'packs'))).toEqual([]);
+ });
+});
diff --git a/apps/desktop/scripts/buildCoreManifest.mjs b/apps/desktop/scripts/buildCoreManifest.mjs
index 1579dbce2af..8fa1fc267aa 100644
--- a/apps/desktop/scripts/buildCoreManifest.mjs
+++ b/apps/desktop/scripts/buildCoreManifest.mjs
@@ -31,8 +31,8 @@ const assertManifest = (manifest) => {
if (problems.length) throw new Error(`core manifest invalid: ${problems.join(', ')}`);
};
-export const readCoreTree = (coreDir) => {
- const { objects, tree: allFiles } = readRendererTree(coreDir);
+export const readCoreTree = (coreDir, options) => {
+ const { objects, tree: allFiles } = readRendererTree(coreDir, options);
const tree = allFiles.filter(
(file) => file.path !== 'manifest.json' && path.posix.basename(file.path) !== '.DS_Store',
);
diff --git a/apps/desktop/scripts/buildCoreV4.mjs b/apps/desktop/scripts/buildCoreV4.mjs
index f7aac7a1b3c..0e8c61f9361 100644
--- a/apps/desktop/scripts/buildCoreV4.mjs
+++ b/apps/desktop/scripts/buildCoreV4.mjs
@@ -1,5 +1,5 @@
import { createHash } from 'node:crypto';
-import { mkdir, writeFile } from 'node:fs/promises';
+import { mkdir, mkdtemp, open, readFile, rename, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { promisify } from 'node:util';
import { constants, zstdCompress, zstdDecompress } from 'node:zlib';
@@ -13,22 +13,34 @@ const decompress = promisify(zstdDecompress);
const hash = (content) => createHash('sha256').update(content).digest('hex');
const PATCH_SCOPE = /^(?:dist\/renderer|cli)\//;
+// Values may be lazy producers so compressed frames need not accumulate in memory.
export async function writeCorePack(entries, output) {
- const chunks = [];
const index = {};
+ const digest = createHash('sha256');
let offset = 0;
- for (const [key, bytes] of [...entries].sort(([a], [b]) => a.localeCompare(b))) {
- index[key] = { compressedSha256: hash(bytes), length: bytes.length, offset };
- chunks.push(bytes);
- offset += bytes.length;
- }
- const bytes = Buffer.concat(chunks);
- const sha256 = hash(bytes);
- const pack = { path: `packs/${sha256}.pack`, sha256, size: bytes.length };
await mkdir(path.join(output, 'packs'), { recursive: true });
- await writeFile(path.join(output, pack.path), bytes);
- for (const frame of Object.values(index)) frame.packSha256 = sha256;
- return { index, pack };
+ const temporary = await mkdtemp(path.join(output, 'packs', '.building-'));
+ try {
+ const file = await open(path.join(temporary, 'pack'), 'w');
+ try {
+ for (const [key, value] of [...entries].sort(([a], [b]) => a.localeCompare(b))) {
+ const bytes = typeof value === 'function' ? await value() : value;
+ index[key] = { compressedSha256: hash(bytes), length: bytes.length, offset };
+ await file.writeFile(bytes);
+ digest.update(bytes);
+ offset += bytes.length;
+ }
+ } finally {
+ await file.close();
+ }
+ const sha256 = digest.digest('hex');
+ const pack = { path: `packs/${sha256}.pack`, sha256, size: offset };
+ await rename(path.join(temporary, 'pack'), path.join(output, pack.path));
+ for (const frame of Object.values(index)) frame.packSha256 = sha256;
+ return { index, pack };
+ } finally {
+ await rm(temporary, { force: true, recursive: true });
+ }
}
async function boundedBody(response, limit) {
@@ -100,7 +112,7 @@ export async function buildCoreV4({
rollout > 1
)
throw new Error('Invalid core release metadata');
- const { objects, tree } = readCoreTree(coreDir);
+ const { objects, tree } = readCoreTree(coreDir, { retainContents: false });
if (!tree.length || tree.some((file) => file.size > 256 * 1024 ** 2))
throw new Error('Invalid core file size');
const old = new Map(previousManifest?.tree.map((file) => [file.path, file.sha256]) ?? []);
@@ -112,10 +124,16 @@ export async function buildCoreV4({
throw new EmptyReleaseError();
const output = path.join(outDir, 'core-v4', platform);
const encoded = new Map();
- for (const [sha256, bytes] of objects) {
- encoded.set(
- sha256,
- await compress(bytes, { params: { [constants.ZSTD_c_compressionLevel]: 19 } }),
+ const readObject = async (sha256) => {
+ const bytes = await readFile(objects.get(sha256));
+ if (hash(bytes) !== sha256) throw new Error(`Core object changed during build: ${sha256}`);
+ return bytes;
+ };
+ for (const sha256 of objects.keys()) {
+ encoded.set(sha256, async () =>
+ compress(await readObject(sha256), {
+ params: { [constants.ZSTD_c_compressionLevel]: 19 },
+ }),
);
}
const { index, pack } = await writeCorePack(encoded, output);
@@ -136,7 +154,7 @@ export async function buildCoreV4({
previousBaseUrl,
fetchImpl,
);
- const patch = await generateZstdPatch(base, objects.get(pair.to.sha256));
+ const patch = await generateZstdPatch(base, await readObject(pair.to.sha256));
if (patch && patch.length < index[pair.to.sha256].length) patchBytes.set(key, patch);
} catch (error) {
console.warn(`Skipping optional patch ${key}: ${error.message}`);
diff --git a/apps/desktop/scripts/buildRendererManifest.mjs b/apps/desktop/scripts/buildRendererManifest.mjs
index 18e18d5b733..1239ecfcfe7 100644
--- a/apps/desktop/scripts/buildRendererManifest.mjs
+++ b/apps/desktop/scripts/buildRendererManifest.mjs
@@ -41,13 +41,14 @@ function walk(dir, files = []) {
return files;
}
-export function readRendererTree(rendererDir) {
+// Path-only indexing lets pack builders load one object at a time.
+export function readRendererTree(rendererDir, { retainContents = true } = {}) {
const objects = new Map();
const tree = walk(rendererDir)
.map((full) => {
const content = readFileSync(full);
const sha256 = sha256Of(content);
- if (!objects.has(sha256)) objects.set(sha256, content);
+ if (!objects.has(sha256)) objects.set(sha256, retainContents ? content : full);
return {
path: path.relative(rendererDir, full).replaceAll('\\', '/'),
sha256,