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(import): batch note writes into per-batch transactions
Elian Doranecb2a85ee697
diff --git a/packages/trilium-core/src/services/import/zip.ts b/packages/trilium-core/src/services/import/zip.tsindex eadc927475..d8ca7616ca 100644--- a/packages/trilium-core/src/services/import/zip.ts+++ b/packages/trilium-core/src/services/import/zip.ts@@ -13,6 +13,7 @@ import noteService from "../../services/notes.js";import { getNoteTitle, newEntityId, removeFileExtension, unescapeHtml } from "../../services/utils/index.js";import { processStringOrBuffer } from "../../services/utils/binary.js";import protectedSessionService from "../protected_session.js";+import { getSql } from "../sql/index.js";import type TaskContext from "../task_context.js";import treeService from "../tree.js";import markdownService from "./markdown.js";@@ -31,6 +32,19 @@ const SPREADSHEET_MIME = "text/x-spreadsheet";// Source mimes rendered from Markdown to HTML on import.const MARKDOWN_MIMES = ["text/markdown", "text/x-markdown", "text/mdx"];+// A note entry whose content has been read (and any async conversion already applied), ready for the+// synchronous saveNote() inside a batch transaction. `mimeOverride` is set when prepareEntry converted a+// raw spreadsheet so saveNote stores it as a spreadsheet instead of re-detecting the raw CSV/XLSX mime.+interface BatchEntry {+ filePath: string;+ content: string | Uint8Array;+ mimeOverride?: string;+}++// A buffered import operation, replayed in order inside one transaction. Directory entries carry no+// content; note entries are BatchEntry. Buffering both preserves the exact zip order across batches.+type BatchItem = { isDirectory: true; filePath: string } | ({ isDirectory: false } & BatchEntry);+interface MetaFile {files: NoteMeta[];}@@ -500,7 +514,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSoureturn content;}- async function saveNote(filePath: string, content: string | Uint8Array) {+ function saveNote(filePath: string, content: string | Uint8Array, mimeOverride?: string) {const { parentNoteMeta, noteMeta, attachmentMeta } = getMeta(filePath);if (noteMeta?.noImport) {@@ -549,12 +563,12 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSouthrow new Error("Unable to resolve mime type.");}- // A raw CSV/XLSX entry still holds its source bytes; convert them to the Univer workbook- // JSON a spreadsheet note stores, then record the spreadsheet mime. Entries from a Trilium- // export already carry workbook JSON and the spreadsheet mime, so they skip this.- if (type === "spreadsheet" && (mime === CSV_MIME || mime === XLSX_MIME)) {- content = await convertSpreadsheetContent(mime, content);- mime = SPREADSHEET_MIME;+ // A raw CSV/XLSX entry is converted to the Univer workbook JSON a spreadsheet note stores by the+ // async prepareEntry() step (so this function can stay synchronous and run inside a batch+ // transaction). When that happened, prepareEntry passes the spreadsheet mime here so the note is+ // stored as a spreadsheet instead of being re-detected as raw CSV/XLSX.+ if (mimeOverride != null) {+ mime = mimeOverride;}if (type !== "file" && type !== "image") {@@ -662,6 +676,27 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou}}+ /**+ * Runs the only asynchronous part of importing a note — converting a raw CSV/XLSX entry into the Univer+ * workbook JSON a spreadsheet note stores — ahead of the synchronous {@link saveNote}. Keeping saveNote+ * synchronous is what lets a whole batch of notes be written inside a single synchronous transaction.+ * Returns the (possibly converted) content plus, when it converted, the mime saveNote should force.+ */+ async function prepareEntry(filePath: string, content: string | Uint8Array): Promise<BatchEntry> {+ const { noteMeta, attachmentMeta } = getMeta(filePath);++ // Attachments, clones and skipped notes return from saveNote before the spreadsheet branch, so+ // they never need conversion. Only an actual note whose mime resolves to a raw spreadsheet does.+ if (!attachmentMeta && !noteMeta?.isClone && !noteMeta?.noImport) {+ const { mime, type: detectedType } = noteMeta ? noteMeta : detectFileTypeAndMime(taskContext, filePath);+ if (resolveNoteType(detectedType) === "spreadsheet" && (mime === CSV_MIME || mime === XLSX_MIME)) {+ return { filePath, content: await convertSpreadsheetContent(mime, content), mimeOverride: SPREADSHEET_MIME };+ }+ }++ return { filePath, content };+ }+const zipProvider = getZipProvider();// Per-phase wall-clock so a single import run reveals where the time goes (logged as one summary line@@ -713,6 +748,41 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSouconst estimatedNoteCount = countImportableNotes(metaFile) || entriesToProcess;taskContext.setTotalCount(entriesToProcess + estimatedNoteCount);+ // Notes are written in batches, each batch in a single synchronous transaction, instead of letting+ // every entity save auto-commit on its own. The per-note BEGIN/COMMIT (and its WAL fsync) dominated+ // import time; batching collapses tens of thousands of commits into a handful (the inner per-entity+ // transactions become cheap savepoints under the outer one). The flush MUST stay synchronous: holding+ // a transaction open across the async readContent() would let concurrent requests on the shared DB+ // connection interleave into the import's transaction. So all async work (reading entries and the+ // spreadsheet conversion in prepareEntry) happens during accumulation, outside the transaction; the+ // flush only replays already-prepared items. A byte cap keeps memory bounded so a multi-GB ZIP is+ // never fully materialised, preserving the per-entry streaming the reader was built for.+ const BATCH_MAX_COUNT = 200;+ const BATCH_MAX_BYTES = 50 * 1024 * 1024;+ let batch: BatchItem[] = [];+ let batchBytes = 0;++ const flushBatch = () => {+ if (batch.length === 0) {+ return;+ }+ const items = batch;+ batch = [];+ batchBytes = 0;++ const saveStart = Date.now();+ getSql().transactional(() => {+ for (const item of items) {+ if (item.isDirectory) {+ saveDirectory(item.filePath);+ } else {+ saveNote(item.filePath, item.content, item.mimeOverride);+ }+ }+ });+ timing.save += Date.now() - saveStart;+ };+await zipProvider.readZipFile(source, async (entry, readContent) => {const filePath = normalizeFilePath(entry.fileName);@@ -721,20 +791,26 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou}if (/\/$/.test(entry.fileName)) {- saveDirectory(filePath);+ batch.push({ isDirectory: true, filePath });} else if (filePath !== "!!!meta.json") {const readStart = Date.now();const content = await readContent();+ const prepared = await prepareEntry(filePath, content);timing.read += Date.now() - readStart;- const saveStart = Date.now();- await saveNote(filePath, content);- timing.save += Date.now() - saveStart;+ batch.push({ isDirectory: false, ...prepared });+ batchBytes += prepared.content.length;++ if (batch.length >= BATCH_MAX_COUNT || batchBytes >= BATCH_MAX_BYTES) {+ flushBatch();+ }}taskContext.increaseProgressCount();}, filenameEncoding);+ flushBatch();+// post-processing increments progress once per created note (a subset of the entries, now known// exactly), so widen the total accordingly to keep the count accurate and let the bar reach 100%taskContext.setTotalCount(entriesToProcess + createdNoteIds.size);