Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
perf(export): bound export memory with input-side archive backpressure
Elian Doranaf1054ddc4e9
diff --git a/apps/server/src/zip_provider.ts b/apps/server/src/zip_provider.tsindex cbbbb49689..d72fe3c29d 100644--- a/apps/server/src/zip_provider.ts+++ b/apps/server/src/zip_provider.ts@@ -6,11 +6,32 @@ import * as yauzl from "yauzl";class NodejsZipArchive implements ZipArchive {readonly #archive: ArchiverZip;+ // Byte sizes of appended entries not yet written out, in FIFO order.+ // archiver processes its queue strictly in order at concurrency 1 and emits+ // exactly one "entry" event per append, so this stays aligned with it.+ readonly #pendingSizes: number[] = [];+ #queuedBytes = 0;+ #capacityWaiter: (() => void) | null = null;++ // Cap how much appended-but-unwritten data archiver holds in its internal+ // queue. The export walk appends the whole note tree synchronously; without+ // this the entire archive (multi-GB) is read into memory before draining.+ static readonly #HIGH_WATER_MARK = 64 * 1024 * 1024; // 64 MiBconstructor() {this.#archive = new ArchiverZip({zlib: { level: 9 }});++ // Fires as each queued entry finishes being written to the output.+ this.#archive.on("entry", () => {+ this.#queuedBytes -= this.#pendingSizes.shift() ?? 0;+ if (this.#capacityWaiter && this.#queuedBytes < NodejsZipArchive.#HIGH_WATER_MARK) {+ const resolve = this.#capacityWaiter;+ this.#capacityWaiter = null;+ resolve();+ }+ });}append(content: string | Uint8Array, options: { name: string; date?: Date }) {@@ -19,9 +40,20 @@ class NodejsZipArchive implements ZipArchive {// byteOffset/byteLength keep the view scoped to this slice, never the// surrounding backing buffer. archiver only reads, so sharing is safe.const payload = typeof content === "string" ? content : Buffer.from(content.buffer, content.byteOffset, content.byteLength);+ const size = typeof content === "string" ? Buffer.byteLength(content) : content.byteLength;+ this.#pendingSizes.push(size);+ this.#queuedBytes += size;this.#archive.append(payload, options);}+ waitForCapacity(): Promise<void> {+ if (this.#queuedBytes < NodejsZipArchive.#HIGH_WATER_MARK) {+ return Promise.resolve();+ }+ // At most one waiter: the export loop awaits this before the next append.+ return new Promise((resolve) => { this.#capacityWaiter = resolve; });+ }+pipe(destination: unknown) {this.#archive.pipe(destination as NodeJS.WritableStream);}diff --git a/apps/standalone/src/lightweight/zip_provider.ts b/apps/standalone/src/lightweight/zip_provider.tsindex d9fb523ffe..b32e352bec 100644--- a/apps/standalone/src/lightweight/zip_provider.ts+++ b/apps/standalone/src/lightweight/zip_provider.ts@@ -15,6 +15,12 @@ class BrowserZipArchive implements ZipArchive {this.#entries[options.name] = typeof content === "string" ? strToU8(content) : content;}+ waitForCapacity(): Promise<void> {+ // zipSync builds the whole archive in memory anyway, so there's nothing+ // to pace against — resolve immediately.+ return Promise.resolve();+ }+pipe(destination: unknown) {this.#destination = destination as ZipOutput;}diff --git a/packages/trilium-core/src/services/export/zip.ts b/packages/trilium-core/src/services/export/zip.tsindex 1f7762e95a..dba9a9b6e6 100644--- a/packages/trilium-core/src/services/export/zip.ts+++ b/packages/trilium-core/src/services/export/zip.ts@@ -313,7 +313,7 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,return content;}- function saveNote(noteMeta: NoteMeta, filePathPrefix: string) {+ async function saveNote(noteMeta: NoteMeta, filePathPrefix: string) {log.info(`Exporting note '${noteMeta.noteId}'`);if (!noteMeta.noteId || noteMeta.title === undefined) {@@ -349,6 +349,10 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,name: filePathPrefix + noteMeta.dataFileName,date: dateUtils.parseDateTime(note.utcDateModified)});++ // Pace the synchronous tree walk against the archive's drain so the+ // whole export isn't buffered into archiver's queue at once.+ await archive.waitForCapacity?.();}taskContext.increaseProgressCount();@@ -368,6 +372,8 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,name: filePathPrefix + attachmentMeta.dataFileName,date: dateUtils.parseDateTime(note.utcDateModified)});++ await archive.waitForCapacity?.();}if (noteMeta.children?.length || 0 > 0) {@@ -379,7 +385,7 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,}for (const childMeta of noteMeta.children || []) {- saveNote(childMeta, `${directoryPath}/`);+ await saveNote(childMeta, `${directoryPath}/`);}}}@@ -462,7 +468,7 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,archive.append(metaFileJson, { name: "!!!meta.json" });- saveNote(rootMeta, "");+ await saveNote(rootMeta, "");provider.afterDone(rootMeta);diff --git a/packages/trilium-core/src/services/zip_provider.ts b/packages/trilium-core/src/services/zip_provider.tsindex 8910cfa43a..93fed2c2ed 100644--- a/packages/trilium-core/src/services/zip_provider.ts+++ b/packages/trilium-core/src/services/zip_provider.ts@@ -16,6 +16,14 @@ export interface ZipArchive {append(content: string | Uint8Array, options: ZipArchiveEntryOptions): void;pipe(destination: unknown): void;finalize(): Promise<void>;+ /**+ * Resolves once the volume of appended-but-not-yet-written data has dropped+ * below the provider's high-water mark. Lets the export loop apply+ * backpressure on the *input* side, so a multi-GB archive isn't fully read+ * into memory before draining begins. Optional: providers that buffer the+ * whole archive anyway (the WASM/browser provider) can omit it.+ */+ waitForCapacity?(): Promise<void>;}export interface FileStream {