Skip to content

Build your personal knowledge base with Trilium Notes

perf(export): stream the zip to the response before appending content

Elian Doran4ce86dd25b47
diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.ts
index 272d9a180d..96aa4c218b 100644
--- a/packages/trilium-core/src/services/export/zip.spec.ts
+++ b/packages/trilium-core/src/services/export/zip.spec.ts
@@ -10,7 +10,8 @@ import type { ExportFormat, NoteMetaFile } from "../../meta.js";
import { getContext } from "../context.js";
import noteService from "../notes.js";
import sql_init from "../sql_init.js";
-import { getZipProvider } from "../zip_provider.js";
+import type { ZipArchive, ZipArchiveEntryOptions, ZipProvider } from "../zip_provider.js";
+import { getZipProvider, initZipProvider } from "../zip_provider.js";
import zip from "./zip.js";
// happy-dom (standalone/WASM) exposes `window`; the Node server suite does not.
@@ -302,6 +303,64 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {
expect(Buffer.compare(entries[attFileName], binaryContent)).toBe(0);
});
+ it("pipes the archive to the response before appending any content", async () => {
+ // Memory efficiency: the archive must start streaming to the response
+ // before note/attachment content is appended, so blobs drain to the
+ // client as they are added rather than all being buffered in memory.
+ const { note } = createNote("root", { title: "StreamOrder", content: "<p>x</p>" });
+ getContext().init(() =>
+ note.saveAttachment({ role: "file", mime: "text/plain", title: "a.txt", content: "data" })
+ );
+ const branch = note.getParentBranches()[0];
+
+ const events: string[] = [];
+ const original = getZipProvider();
+ const spy: ZipProvider = {
+ detectFilenameEncoding: (b) => original.detectFilenameEncoding(b),
+ readZipFile: (b, fn, enc) => original.readZipFile(b, fn, enc),
+ createFileStream: (p) => original.createFileStream(p),
+ createZipArchive() {
+ const real = original.createZipArchive();
+ const wrapper: ZipArchive = {
+ append(content: string | Uint8Array, options: ZipArchiveEntryOptions) {
+ events.push(`append:${options.name}`);
+ real.append(content, options);
+ },
+ pipe(dest: unknown) {
+ events.push("pipe");
+ real.pipe(dest);
+ },
+ finalize() {
+ events.push("finalize");
+ return real.finalize();
+ }
+ };
+ return wrapper;
+ }
+ };
+
+ initZipProvider(spy);
+ try {
+ const taskContext = (await import("../task_context.js")).default;
+ const ctx = new taskContext("no-progress-reporting", "export", null);
+ const res = new FakeResponse();
+ const done = collect(res);
+ await zip.exportToZip(ctx, branch, "html", res as unknown as Record<string, unknown>);
+ await done;
+ } finally {
+ initZipProvider(original);
+ }
+
+ // The pipe is the very first archive operation and precedes every append.
+ const pipeIdx = events.indexOf("pipe");
+ const firstAppendIdx = events.findIndex((e) => e.startsWith("append:"));
+ expect(pipeIdx).toBe(0);
+ expect(firstAppendIdx).toBeGreaterThan(pipeIdx);
+ // Content really was appended (note data + attachment), and finalize closes it.
+ expect(events).toContain("append:!!!meta.json");
+ expect(events[events.length - 1]).toBe("finalize");
+ });
+
it("keeps the extension on very long multi-byte titles within the 255-byte limit", async () => {
// A title of 3-byte CJK characters long enough that, once the upstream
// 255-byte sanitize cap fills the base, appending the extension would
diff --git a/packages/trilium-core/src/services/export/zip.ts b/packages/trilium-core/src/services/export/zip.ts
index 2a41340a50..5402e0a17a 100644
--- a/packages/trilium-core/src/services/export/zip.ts
+++ b/packages/trilium-core/src/services/export/zip.ts
@@ -433,14 +433,6 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,
}
}
- const metaFileJson = JSON.stringify(metaFile, null, "\t");
-
- archive.append(metaFileJson, { name: "!!!meta.json" });
-
- saveNote(rootMeta, "");
-
- provider.afterDone(rootMeta);
-
const note = branch.getNote();
const zipFileName = `${branch.prefix ? `${branch.prefix} - ` : ""}${note.getTitleOrProtected()}.zip`;
@@ -449,7 +441,21 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,
res.setHeader("Content-Type", "application/zip");
}
+ // Start streaming to the destination *before* appending content. The archiver
+ // drains each appended blob as it is added, so memory stays bounded instead of
+ // buffering the whole export. Trade-off: a failure while reading content mid-
+ // export can no longer produce a clean HTTP error (bytes are already on the
+ // wire); the validation that can fail cleanly runs in the try/catch above.
archive.pipe(res);
+
+ const metaFileJson = JSON.stringify(metaFile, null, "\t");
+
+ archive.append(metaFileJson, { name: "!!!meta.json" });
+
+ saveNote(rootMeta, "");
+
+ provider.afterDone(rootMeta);
+
await archive.finalize();
taskContext.taskSucceeded(null);