Skip to content

Build your personal knowledge base with Trilium Notes

perf(export): skip deflate for already-compressed entries; default level 9->6

Elian Dorana4b3a43e5e71
diff --git a/apps/server/src/zip_provider.ts b/apps/server/src/zip_provider.ts
index d72fe3c29d..83ed1daa8e 100644
--- a/apps/server/src/zip_provider.ts
+++ b/apps/server/src/zip_provider.ts
@@ -1,4 +1,4 @@
-import type { FileStream, ZipArchive, ZipEntry, ZipProvider } from "@triliumnext/core/src/services/zip_provider.js";
+import type { FileStream, ZipArchive, ZipArchiveEntryOptions, ZipEntry, ZipProvider } from "@triliumnext/core/src/services/zip_provider.js";
import { ZipArchive as ArchiverZip } from "archiver";
import fs from "fs";
import type { Stream } from "stream";
@@ -20,7 +20,10 @@ class NodejsZipArchive implements ZipArchive {
constructor() {
this.#archive = new ArchiverZip({
- zlib: { level: 9 }
+ // Level 6 (zlib default) is the speed/ratio sweet spot; level 9 costs
+ // ~2x the CPU for <2% smaller output. Already-compressed entries skip
+ // deflate entirely via the per-entry `store` flag below.
+ zlib: { level: 6 }
});
// Fires as each queued entry finishes being written to the output.
@@ -34,7 +37,7 @@ class NodejsZipArchive implements ZipArchive {
});
}
- append(content: string | Uint8Array, options: { name: string; date?: Date }) {
+ append(content: string | Uint8Array, options: ZipArchiveEntryOptions) {
// Wrap the Uint8Array in a Buffer view sharing the same memory rather
// than copying it (Buffer.from(uint8array) would allocate a full copy).
// byteOffset/byteLength keep the view scoped to this slice, never the
@@ -43,6 +46,8 @@ class NodejsZipArchive implements ZipArchive {
const size = typeof content === "string" ? Buffer.byteLength(content) : content.byteLength;
this.#pendingSizes.push(size);
this.#queuedBytes += size;
+ // `store` (and `date`) pass straight through: archiver preserves extra
+ // entry-data fields and zip-stream switches to the STORE method when set.
this.#archive.append(payload, options);
}
diff --git a/apps/standalone/src/lightweight/zip_provider.ts b/apps/standalone/src/lightweight/zip_provider.ts
index b32e352bec..b4cf84e058 100644
--- a/apps/standalone/src/lightweight/zip_provider.ts
+++ b/apps/standalone/src/lightweight/zip_provider.ts
@@ -8,11 +8,13 @@ type ZipOutput = {
};
class BrowserZipArchive implements ZipArchive {
- readonly #entries: Record<string, Uint8Array> = {};
+ readonly #entries: Record<string, Uint8Array | [Uint8Array, { level: 0 }]> = {};
#destination: ZipOutput | null = null;
- append(content: string | Uint8Array, options: { name: string }) {
- this.#entries[options.name] = typeof content === "string" ? strToU8(content) : content;
+ append(content: string | Uint8Array, options: { name: string; store?: boolean }) {
+ const data = typeof content === "string" ? strToU8(content) : content;
+ // fflate honors a per-entry level; level 0 stores the entry uncompressed.
+ this.#entries[options.name] = options.store ? [data, { level: 0 }] : data;
}
waitForCapacity(): Promise<void> {
@@ -30,7 +32,7 @@ class BrowserZipArchive implements ZipArchive {
throw new Error("ZIP output destination not set.");
}
- const content = zipSync(this.#entries, { level: 9 });
+ const content = zipSync(this.#entries, { level: 6 });
if (typeof this.#destination.send === "function") {
this.#destination.send(content);
diff --git a/packages/trilium-core/src/services/export/zip.spec.ts b/packages/trilium-core/src/services/export/zip.spec.ts
index b9ae6edbfc..85a12ed5b2 100644
--- a/packages/trilium-core/src/services/export/zip.spec.ts
+++ b/packages/trilium-core/src/services/export/zip.spec.ts
@@ -12,7 +12,7 @@ import noteService from "../notes.js";
import sql_init from "../sql_init.js";
import type { ZipArchive, ZipArchiveEntryOptions, ZipProvider } from "../zip_provider.js";
import { getZipProvider, initZipProvider } from "../zip_provider.js";
-import zip from "./zip.js";
+import zip, { shouldStoreUncompressed } from "./zip.js";
// happy-dom (standalone/WASM) exposes `window`; the Node server suite does not.
const isBrowserRuntime = typeof window !== "undefined";
@@ -520,3 +520,39 @@ describe.skipIf(isBrowserRuntime)("zip export (real DB)", () => {
});
});
});
+
+describe("shouldStoreUncompressed", () => {
+ it("stores already-compressed payloads uncompressed", () => {
+ for (const mime of [
+ "image/jpeg", "image/png", "image/gif", "image/webp", "image/avif",
+ "video/mp4", "video/webm", "audio/mpeg", "audio/ogg",
+ "application/pdf", "application/zip", "application/gzip",
+ "application/x-7z-compressed", "font/woff2",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // docx
+ "application/vnd.oasis.opendocument.spreadsheet", // ods
+ "application/epub+zip"
+ ]) {
+ expect(shouldStoreUncompressed(mime), mime).toBe(true);
+ }
+ });
+
+ it("compresses text and other deflate-friendly payloads", () => {
+ for (const mime of [
+ "text/html", "text/plain", "text/markdown", "application/json",
+ "application/xml", "application/javascript",
+ "image/svg+xml", "image/bmp", "image/x-icon", "image/tiff",
+ "audio/wav", "audio/x-wav", "audio/aiff"
+ ]) {
+ expect(shouldStoreUncompressed(mime), mime).toBe(false);
+ }
+ });
+
+ it("normalizes case and ignores parameters, and treats missing mime as compressible", () => {
+ expect(shouldStoreUncompressed("IMAGE/JPEG")).toBe(true);
+ expect(shouldStoreUncompressed("image/png; charset=binary")).toBe(true);
+ expect(shouldStoreUncompressed(" text/html ; charset=utf-8 ")).toBe(false);
+ expect(shouldStoreUncompressed(undefined)).toBe(false);
+ expect(shouldStoreUncompressed(null)).toBe(false);
+ expect(shouldStoreUncompressed("")).toBe(false);
+ });
+});
diff --git a/packages/trilium-core/src/services/export/zip.ts b/packages/trilium-core/src/services/export/zip.ts
index fd5612068a..69e3fbbc30 100644
--- a/packages/trilium-core/src/services/export/zip.ts
+++ b/packages/trilium-core/src/services/export/zip.ts
@@ -347,7 +347,8 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,
archive.append(content as string | Uint8Array, {
name: filePathPrefix + noteMeta.dataFileName,
- date: dateUtils.parseDateTime(note.utcDateModified)
+ date: dateUtils.parseDateTime(note.utcDateModified),
+ store: shouldStoreUncompressed(noteMeta.mime)
});
// Pace the synchronous tree walk against the archive's drain so the
@@ -370,7 +371,8 @@ async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch,
archive.append(content, {
name: filePathPrefix + attachmentMeta.dataFileName,
- date: dateUtils.parseDateTime(note.utcDateModified)
+ date: dateUtils.parseDateTime(note.utcDateModified),
+ store: shouldStoreUncompressed(attachmentMeta.mime)
});
await archive.waitForCapacity?.();
@@ -538,3 +540,55 @@ export default {
exportToZipFile,
exportBranchToZipFile
};
+
+/**
+ * Whether a payload of the given MIME type is already compressed and should be
+ * stored uncompressed in a ZIP rather than re-deflated. Deflating these wastes
+ * CPU (often the export bottleneck) for negligible — sometimes negative — size
+ * change. Conservative: anything not known-compressed returns false and is
+ * compressed normally, so text/HTML/SVG/JSON/code all still deflate.
+ */
+export function shouldStoreUncompressed(mime: string | undefined | null): boolean {
+ if (!mime) {
+ return false;
+ }
+ const m = mime.toLowerCase().split(";")[0].trim();
+
+ // Codec-compressed media. PCM/AIFF are uncompressed, so let them deflate.
+ if (m.startsWith("video/")) {
+ return true;
+ }
+ if (m.startsWith("audio/")) {
+ return !UNCOMPRESSED_AUDIO.has(m);
+ }
+
+ return ALREADY_COMPRESSED.has(m) || isZipBasedContainer(m);
+}
+
+// Office / e-book / package formats that are ZIP containers under the hood.
+function isZipBasedContainer(mime: string): boolean {
+ return (
+ mime.startsWith("application/vnd.openxmlformats-officedocument.") || // docx/xlsx/pptx
+ mime.startsWith("application/vnd.oasis.opendocument.") || // odt/ods/odp
+ mime === "application/epub+zip" ||
+ mime === "application/java-archive" ||
+ mime === "application/vnd.android.package-archive"
+ );
+}
+
+const UNCOMPRESSED_AUDIO = new Set([
+ "audio/wav", "audio/x-wav", "audio/wave", "audio/aiff", "audio/x-aiff"
+]);
+
+const ALREADY_COMPRESSED = new Set([
+ // Raster images (SVG/BMP/ICO/TIFF deliberately excluded — they deflate well)
+ "image/jpeg", "image/png", "image/gif", "image/webp",
+ "image/avif", "image/heic", "image/heif", "image/jp2", "image/apng",
+ // Archives / compressed streams
+ "application/zip", "application/x-zip-compressed", "application/gzip",
+ "application/x-gzip", "application/x-bzip2", "application/x-xz",
+ "application/x-7z-compressed", "application/x-rar-compressed",
+ "application/x-apple-diskimage",
+ // Already-compressed documents / fonts
+ "application/pdf", "font/woff", "font/woff2"
+]);
diff --git a/packages/trilium-core/src/services/zip_provider.ts b/packages/trilium-core/src/services/zip_provider.ts
index 93fed2c2ed..5addbc8836 100644
--- a/packages/trilium-core/src/services/zip_provider.ts
+++ b/packages/trilium-core/src/services/zip_provider.ts
@@ -10,6 +10,13 @@ export interface ZipEntry {
export interface ZipArchiveEntryOptions {
name: string;
date?: Date;
+ /**
+ * Store the entry uncompressed (ZIP STORE method) instead of deflating it.
+ * Set for already-compressed payloads (JPEG/PNG, video, PDFs, zip-based
+ * office docs…) where zlib spends CPU for ~0% size reduction. Providers that
+ * can't control per-entry compression may ignore it.
+ */
+ store?: boolean;
}
export interface ZipArchive {